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

Umb*_*lla 9 javascript typescript

我有一个这样的对象

const MY_OBJECT = {
  'key': 'key val',
  'anotherKey': 'anotherKey val',
};
Run Code Online (Sandbox Code Playgroud)

有没有办法从这个对象'key' | 'anotherKey'类型中提取?

Tit*_*mir 16

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

const MY_OBJECT = {
    'key': 'key val',
    'anotherKey': 'anotherKey val',
};
type MY_OBJECT_KEYS = keyof typeof MY_OBJECT // "key" | "anotherKey"
Run Code Online (Sandbox Code Playgroud)