【问题标题】:Get the type of numeric object properties as strings in typescript?在打字稿中将数字对象属性的类型作为字符串获取?
【发布时间】:2022-01-25 21:06:18
【问题描述】:

有一个类似的对象:

const obj = {
   1: "one",
   2: "two",
   3: "three",
}

type Keys = keyof typeof obj; // type of Key is 1 | 2 | 3

我如何让Keys 成为(字符串)"1" | "2" | "3" 类型以便自动完成?

【问题讨论】:

    标签: typescript types


    【解决方案1】:

    由于TypeScript 4.1,可以使用Template Literal Types

    const obj = {
       1: "one",
       2: "two",
       3: "three",
    }
    
    type Keys = `${keyof typeof obj}`;
    const value: Keys = "1";
    

    【讨论】:

      猜你喜欢
      • 2020-11-21
      • 2019-10-15
      • 2021-12-06
      • 2019-03-10
      • 2020-08-15
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 2022-01-26
      相关资源
      最近更新 更多