Home > Net >  Typescript infer return type of an object based on its key
Typescript infer return type of an object based on its key

Time:06-01

What I want to do is very simple, I have a class called Config. Inside this class, I have some fields and each one have a different type.

Right now I have a method that basically accepts the field name as the argument and return the value of it, like this:

get(key: Extract<keyof Config, string>): any {
  // this.config is my Config class
  return this.config[key];
}

The argument works great, I get auto complete for all the field names in my Config class, but based on that, I want to infer the return type of this function. So let's say that the field I'm trying to get has the DbConfig type, when I call this get method, I want the return to be DbConfig as well, and not use any like I did in the example above.

Is that possible? If so, how to do that?

CodePudding user response:

You can use the key parameter as a generic type K. K can then be used to index Config for the return type.

function get<K extends keyof Config & string>(key: K): Config[K] {
  return config[key]
}

Playground

  • Related