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 ?
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 .
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.
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 .
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With