【发布时间】:2022-01-06 15:28:38
【问题描述】:
我正在尝试编写一个函数来根据键对对象上的各种数组进行排序。这是我的代码:
const sort = (value: keyof TargetTypes) => {
const sortedTargetsList = targetsList && [...targetsList]
sortedTargetsList?.sort((a, b) => a[value].localeCompare(b[value]))
}
然后我在悬停localeComparesaying (Google Trad) 时出错:
Property 'localeCompare' does not exist on type 'string | boolean | string [] | [] | {platform: string; link: string; userId: string; } [] '.
Property 'localeCompare' does not exist on type 'false' .ts (2339)
尝试了各种方法,但找不到方法,甚至无法理解出了什么问题。我已经尝试过像这样对值进行硬编码,它可以工作:a['targetName']
感谢你们的帮助。
【问题讨论】:
-
你能提供你想要排序的数组吗?
-
@shobe 我不能给你看真实的,但它是这样的:` const targetsList = [ { targetName: "Target 1", createdAt: "2022-05-01" }, { targetName: "Target 2", createdAt: "2022-05-02" } ] ` 很常见..
-
您可能在对象中还有另一个键,其类型不是字符串。所以试着像这样写比较: typeof a[value] === "string" && typeof b[value] === "string" ? a[value].localeCompare(b[value]) : 1;
标签: javascript reactjs typescript