简体   繁体   中英

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

I've got an object like this

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

Is there a way to extract from this object 'key' | 'anotherKey' 'key' | 'anotherKey' type ?

To get a type that is a union keys of a variable you need to use keyof typeof variableName .

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

to achieve what you are looking for you just have to get rid of quotation marks in your object:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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