我有这个keyBy
功能:
export function keyBy<T>(items: T[] | undefined, extractId: (item: T) => number): Record<number, T> {
const obj: Record<number, T> = {};
if (items) {
items.forEach(item => {
const id = extractId(item);
obj[id] = item;
});
}
return obj;
}
它可以用于将对象数组转换为这些对象的字典,以您想要的任何内容为关键字.例如:
const users = [user1, user2, ...]l
const usersById = keyBy(users, u => u.id);
现在我想更改此函数,使其不仅可以使用ID之类的数字键,还可以使用字符串:
export function keyBy<Key extends string | number, T>(items: T[] | undefined, extractId: (item: T) => Key): Record<Key, T> {
const obj: Record<Key, T> = {};
if (items) {
items.forEach(item => {
const id = extractId(item);
obj[id] = item;
});
}
return obj;
}
这会产生错误Type '{}' is not assignable to type 'Record<Key, T>'. ts(2322)
.为什么这不管用?
我认为问题是现在每id
个可以是一个字符串或一个数字,而我想要的是所有的ID要么是一个字符串要么是一个数字,但当然它们都是同一类型的.