元素隐式地具有“ any”类型,因为类型“ any”的表达式不能用于索引类型“ Item”

时间:2020-10-19 11:38:56

标签: reactjs typescript

有很多帖子回答类似的问题,但是我无法在我的代码中使用它。

我想基于字符串为对象建立索引,并且遇到此错误:

元素隐式地具有“ 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的类型?

1 个答案:

答案 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]));
}