【问题标题】:construct string union type from keys of custom type in TypeScript从 TypeScript 中自定义类型的键构造字符串联合类型
【发布时间】:2021-07-05 17:57:51
【问题描述】:

如何在 TypeScript 中基于自定义类型的键构造字符串联合类型?当然,只有当它们都是字符串时才有效。

假设我有这个:

type MyFields {
  name: string
  email: string
  password: string
}

我怎么能生成这样的东西:

type MyFieldsKeys = 'name' | 'email' | 'password'

这样的功能存在吗?

这与Record 所做的相反——例如,我可以通过MyFields = Record<MyFieldsKeys, string> 使用RecordMyfieldsKeys 生成MyFields

【问题讨论】:

    标签: typescript


    【解决方案1】:

    使用keyof 生成键的字符串或数字文字联合。

    type MyFields = {
      name: string
      email: string
      password: string
    }
    
    type MyfieldsKeys = keyof MyFields;
    

    【讨论】:

      猜你喜欢
      • 2019-02-04
      • 1970-01-01
      • 2019-10-09
      • 2021-10-27
      • 2016-07-22
      • 2023-02-15
      • 2018-03-01
      • 2019-10-14
      • 2020-07-31
      相关资源
      最近更新 更多