Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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[]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'); 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading