Home > Enterprise >  How to extract exact union type from typed object key strings in typescript?
How to extract exact union type from typed object key strings in typescript?

Time:06-04

I've got an object like this

interface MY_OBJECT_INTERFACE {
  [key: string]: string
}
const MY_OBJECT: MY_OBJECT_INTERFACE = {
  'key': 'key val',
  'anotherKey': 'anotherKey val',
};

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

"keyof typeof MY_OBJECT" didn't works.

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

CodePudding user response:

As MY_OBJECT_INTERFACE allows any string as key, it's not possible to extract the type of the keys. If the keys are always known you could just change MY_OBJECT_INTERFACE to somthing like @LihnNguyen suggested and then the you can go with the related issue, but I guess that's not what you're looking for.

If the object is dynamic (which I assume it is), the only thing you could do is use Object.keys to get an array of the keys and then work with that. This is of course no type and only a string array, but at least to my knowledge it's the best typescript can do for you.

CodePudding user response:

You try this way

interface MY_OBJECT_INTERFACE {
  key: string,
  anotherKey: string
}
const MY_OBJECT<MY_OBJECT_INTERFACE> = {
  'key': 'key val',
  'anotherKey': 'anotherKey val',
};
  • Related