Let's say I have an object like the following:
let obj = {
method1: () => { return "method1 called" },
method2: () => { return "method2 called" },
method3: () => { return "method3 called" },
}
I want to declare a variable, which value can only be one of the keys present in obj
.
Manually, I can do it like this:
let myVar : "method1" | "method2" | "method3";
But is there any way I can declare this in a dynamic way? So that any of the method I'd add in obj
would be found as valid value for myVar
.
Use the keyof typeof syntax to create a type from an object's keys, e.g. type Keys = keyof typeof person . The keyof typeof syntax returns a type that represents all of the object's keys as strings.
The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. Declare its type and value in one statement.
keyof is a keyword in TypeScript which is used to extract the key type from an object type.
In Typescript, Type assertion is a technique that informs the compiler about the type of a variable. Type assertion is similar to typecasting but it doesn't reconstruct code. You can use type assertion to specify a value's type and tell the compiler not to deduce it.
You can use the keyof
operator, this will give you a type with all the property names of another type. To get the type of obj
we use the typeof
operator.
let myVar : keyof typeof obj; // Actual type will be "method1" | "method2" | "method3"
If you add more keys to the object the type of myVar
will update automatically. But this only works if the keys are known at compile time.
For more about keyof
see here.
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