繁体   English   中英

如何从打字稿中的对象键字符串中提取确切的联合类型?

[英]How to extract exact union type from object key strings in typescript?

我有一个这样的物体

const MY_OBJECT = {
  'key': 'key val',
  'anotherKey': 'anotherKey val',
};

有没有一种方法可以从此对象'key' | 'anotherKey'提取'key' | 'anotherKey' 'key' | 'anotherKey'类型?

要获得作为变量的联合键的类型,您需要使用keyof typeof variableName

const MY_OBJECT = {
    'key': 'key val',
    'anotherKey': 'anotherKey val',
};
type MY_OBJECT_KEYS = keyof typeof MY_OBJECT // "key" | "anotherKey"

要实现您想要的功能,您只需要去除对象中的引号即可:

const MY_OBJECT = {
  key: 'key val',
  anotherKey: 'anotherKey val',
};
console.log(keyof MY_OBJECT); // "key" | "anotherKey"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM