【问题标题】:How to infer the type of object keys from a string array如何从字符串数组中推断对象键的类型
【发布时间】:2020-01-21 11:24:37
【问题描述】:

我有以下功能:

    const infer = (...params: string[]): Record<string, string> => {
      const obj: Record<string, string> = {};
      // Put all params as keys with a random value to obj
      // [...]
      return obj;
    }

此函数将接受 n 个字符串并返回一个对象,该对象恰好包含这些字符串作为键,具有随机值。

所以infer("abc", "def") 可能会返回{"abc": "1337", "def":"1338"}

有什么方法可以推断返回类型以从此函数获得完整的类型安全性?该函数的代码保证每个键都将出现在返回的对象中,并且每个值都将是一个字符串。

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    你可以这样声明:

    const infer = <T extends string[]>(...params: T): Record<T[number], string> => {
      const obj: Record<string, string> = {};
      // Put all params as keys with a random value to obj
      // [...]
      return obj;
    };
    
    const t = infer("a", "b", "c") // const t: Record<"a" | "b" | "c", string>
    

    Playground

    【讨论】:

    • 太棒了,你能解释一下T[number] 部分的作用吗?
    • 当然。如果您有type MyTuple = ["a", "b", "c"],您可以使用lookup/index access operator 通过它们的数字索引值访问项目类型,例如MyTuple[0] 的类型为 "a"MyTuple[number] 中的 number 仅代表所有可能的数字索引值,因此 MyTuple[number] 是所有可能项类型的并集,它们是您想要的字符串值。
    • 如果我将键作为单个列表传递怎么办?如何获得相同的输出?
    • @etarrowo 您可以从infer 中删除其余参数并让T 扩展字符串,如here
    • 太棒了,谢谢@ford04 这个让我有点困惑
    猜你喜欢
    • 2022-07-19
    • 2022-01-05
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    相关资源
    最近更新 更多