【问题标题】:typescript uses generics to reorganize read-only array typestypescript 使用泛型重组只读数组类型
【发布时间】:2022-11-18 17:05:46
【问题描述】:

我试图重构只读数组的类型,但没有成功:

const store: Record<string, any> = {
  aaa: '123',
  bbb: null,
  ccc: []
}

const getValues = <Keys extends readonly string[]>(keys: Keys): ReadonlyArray<[Keys[number], unknown]> => {
  return keys.map((key) => ([key, key in store ? store[key] : null]))
}

const keyArr = ['aaa', 'bbb'] as const
getValues(keyArr)  // current getValues function types:  const getValues: <readonly ["aaa", "bbb"]>(keys: readonly ["aaa", "bbb"]) => readonly ["aaa" | "bbb", unknown][]

// I want:  const getValues: <readonly ["aaa", "bbb"]>(keys: readonly ["aaa", "bbb"]) => readonly [["aaa", unknown], ["bbb", unknown]]

这是打字稿Playground code link

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以使用 mapped type 映射元组。使用映射类型映射元组类型也会生成一个元组作为结果 since TypeScript 3.1

    const getValues = <Keys extends readonly string[]>(keys: Keys) => {
      return keys.map((key) => (
        [key, key in store ? store[key] : null])
      ) as { [K in keyof Keys]: [Keys[K], unknown] }
    }
    

    TypeScript 无法正确理解结果数组的类型与返回类型匹配。所以需要类型断言。


    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-22
      • 2022-12-03
      • 2021-04-23
      • 2020-05-30
      • 2020-04-21
      • 2019-09-08
      • 2019-05-15
      • 1970-01-01
      相关资源
      最近更新 更多