Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript, declare a variable type must be key of an object

Tags:

typescript

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.

like image 223
chateau Avatar asked Jan 26 '18 12:01

chateau


People also ask

How do you define a type of key of an object in TypeScript?

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.

How do you declare a variable as a object in TypeScript?

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.

What is Keyof typeof in TypeScript?

keyof is a keyword in TypeScript which is used to extract the key type from an object type.

What is type assertion in TypeScript?

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.


1 Answers

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.

like image 73
Titian Cernicova-Dragomir Avatar answered Oct 29 '22 18:10

Titian Cernicova-Dragomir