简体   繁体   中英

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

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM