【问题标题】:Turn typescript interface property types into union [duplicate]将打字稿接口属性类型转换为联合[重复]
【发布时间】:2022-01-04 17:56:23
【问题描述】:

我有这个接口,我想根据它包含的键类型生成一个新类型。

interface SomeType {
  abc: string;
  def: number;
  ghi: boolean;
}

要生成的类型:

type SomeOtherType = string | number | boolean

这在打字稿中可行吗?

【问题讨论】:

  • 这就是keyof的全部目的

标签: typescript


【解决方案1】:

您可以尝试使用 keyof 运算符进行索引:

interface SomeType {
  abc: string;
  def: number;
  ghi: "sdf";
}

type t = SomeType[keyof SomeType];

类型 t 将被假定为来自对象值的类型联合:

https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgMoHsC2EAqBPABxQG8AoZZOAIwQC5kBnMKUAcwG5zkATCGekAFdMVaJwqsAFsHoAiBtxizOAX1KkwhFGGQBeNFlxaA2gGsIedDAPZ8RALrsgA

【解决方案2】:

您可以使用一个技巧来生成接口的值:

interface SomeType {
  abc: string;
  def: number;
  ghi: boolean;
}

//First generate a type that works as a "valueof" (similar to keyof)
type ValueOf<T> = T[keyof T];

//Then obtain the values
type Values = ValueOf<SomeType> // Values = string | number | boolean
//ValueOf re-usable component, however it is enough also SomeType[keyof SomeType]

//If you need the keys on the other hand "keyof" is enough:
type Keys = keyof SomeType // Keys = 'abc' | 'def' | 'ghi'

【讨论】:

    猜你喜欢
    • 2017-09-16
    • 2020-10-16
    • 2019-07-23
    • 1970-01-01
    • 2020-05-21
    • 2021-06-03
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多