有很多帖子回答类似的问题,但是我无法在我的代码中使用它。
我想基于字符串为对象建立索引,并且遇到此错误:
元素隐式地具有“ any”类型,因为类型“ any”的表达式不能用于索引类型“ Item”。
我的功能:
export type ListItems = Array<Item>;
export interface Item {
id: number;
name: string;
}
export function sortList(list: ListItems, sortkey: string): ListItems {
return list.sort((a, b) => a[sortkey].localeCompare(b[sortkey]));
}
如何使用Item
使TypeScript索引sortKey
的类型?
答案 0 :(得分:1)
您可以限制可以使用keyof
传递的属性:
export function sortList(list: ListItems, sortKey: keyof Item): ListItems {
return list.sort((a, b) => a[sortKey].localeCompare(b[sortKey]));
}
但是,您将遇到的问题是它正在使用localeCompare
,它假定值是一个字符串。由于sortKey
可以引用id
(是一个数字),因此localCompare
无效。因此,您有几种选择:
toString
。对于选项2,您可以使用类似的内容:
type ItemStringsOnly = Pick<Item, {
[K in keyof Item]: Item[K] extends string ? K : never
}[keyof Item]>;
export function sortList(list: ListItems, sortKey: keyof ItemStringsOnly): ListItems {
return list.sort((a, b) => a[sortKey].localeCompare(b[sortKey]));
}