1

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!

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This only seems to work when the field name is directly given but not when it comes from elsewhere, e.g.: ['field1', 'field2'].map(field => getValue(state, field)) complains that Argument of type 'string' is not assignable to parameter of type 'keyof IState'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.