Typescript definition for typeof keyof T

I have a system which can work with different "state" objects, an example instance of such a state object could be:

interface MyState {
  name: string;
  age: number;
  things: string[];
}

I also have a class to interact with various state implementations

class StateManager<T> {

  state: T;

  pick(field: keyof T) {
    return this.state[field];
  }
}

I would like to type hint the exact output of pick, at the moment I am getting a union of all possible types. string | number | string[]

Is there something like

pick<K extends keyof T>(field: keyof T): typeof K

Such that pick('name') would be string and pick('age') is number

>Solution :

You can try creating a indexed access type that maps specific keys to their corresponding value types:

interface MyState {
  name: string;
  age: number;
  things: string[];
}

type ValueOf<T> = T[keyof T];

class StateManager<T> {

  state: T;

  pick<K extends keyof T>(field: K): T[K] {
    return this.state[field];
  }
}

const manager = new StateManager<MyState>();

const name: string = manager.pick('name');  
const age: number = manager.pick('age');   
const things: string[] = manager.pick('things'); 

Leave a Reply