Gustavo Mendonça
Gustavo Mendonça

Reputation: 2091

Infer return type of an object based on its key

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?

Upvotes: 2

Views: 1398

Answers (1)

Tobias S.
Tobias S.

Reputation: 23825

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

Upvotes: 1

Related Questions