Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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' type ?

like image 709
Umbrella Avatar asked May 14 '19 08:05

Umbrella


People also ask

What is the union type on TypeScript?

A union type describes a value that can be one of several types. We use the vertical bar ( | ) to separate each type, so number | string | boolean is the type of a value that can be a number , a string , or a boolean .

Can I check a type against a union type in TypeScript?

We can differentiate between types in a union with a type guard. A type guard is a conditional check that allows us to differentiate between types. And in this case, a type guard lets us figure out exactly which type we have within the union.

How do you check if a key is in an object TypeScript?

Use the in operator to check if a key exists in an object, e.g. "key" in myObject . The in operator will return true if the key is present in the object, otherwise false is returned. Copied! The syntax used with the in operator is: string in object .

How check string is member of union type?

To check if a string is in a union type:Create a reusable function that takes a string as a parameter. Add the values of the union type of an array. Use the includes() method to check if the string is contained in the array.


Video Answer


1 Answers

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"
like image 110
Titian Cernicova-Dragomir Avatar answered Sep 27 '22 22:09

Titian Cernicova-Dragomir