将打字稿接口属性类型转换为联合[重复]

2023-12-27

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

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

输入生成:

type SomeOtherType = string | number | boolean

这在打字稿中可能吗?


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

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

type t = SomeType[keyof SomeType];

The type t will be assumed as a type union that comes from the values of the object: enter image description here

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将打字稿接口属性类型转换为联合[重复] 的相关文章

随机推荐