【问题标题】:Using localCompare with key passed in a function将 localCompare 与函数中传递的键一起使用
【发布时间】: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


【解决方案1】:

通过这样做解决,不确定这是否是更好的方法...有点不喜欢 eslin disable 行,但我没有任何线索..

const sort = (value: keyof TargetTypes) => {
  setTargetsList(
    targetsList &&
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
      [...targetsList].sort((a: any, b: any) =>
        a[value].localeCompare(b[value]),
      ),
  )
}  

与@shobe 相比,我更喜欢这个解决方案,因为它在输入“sort(”以选择可用键后给我建议。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    • 2020-10-22
    • 2018-08-24
    • 2012-08-11
    • 2010-12-13
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多