marco burrometo
marco burrometo

Reputation: 1135

Typescript get object property type from name

I'm trying to do a type inference function in typescript inside a reactive bus class.

Here is an example:

  // This is the function
  getValue<T>(data: T, key: keyof T) {
    return data[key];
  }

  // This is the test
  interface IState {
    field1: number;
    field2: string;
  }

  const state: IState = {
    field1: 123,
    field2: 'abc'
  };

  const x = getValue(state, 'field1');

Key variable is infered succesfully (i cannot type different values than interface keys). The problem is that doing this the type of 'x' variable is number|string but i'm expecting number.

Am i missing something? Is it possible?

Thank you!

Upvotes: 1

Views: 8502

Answers (1)

Mikhail Burshteyn
Mikhail Burshteyn

Reputation: 5012

Your implementation of getValue has inferred return type of T[keyof T], which is number|string.

What you want can be achieved the following way:

function getValue<T, K extends keyof T>(data: T, key: K) {
  return data[key];
}

// This is the test
interface IState {
  field1: number;
  field2: string;
}

const state: IState = {
  field1: 123,
  field2: 'abc'
};

const x = getValue(state, 'field1');

This way, the return type of getValue is T[K], where K is inferred to be one specific key in keyof T.

Upvotes: 4

Related Questions