Microshine
Microshine

Reputation: 799

How to write TypeScript `get` function for Map object?

Is it possible to do something like this in TypeScript?

interface IPerson {
  name: string;
  age: number;
}

declare class Map<T> {
  get(name: keyof T): any // ? return type
}

Result I need

const map = new Map<IPerson>();
map.get("name"); // string
map.get("age"); // number

Upvotes: 0

Views: 269

Answers (1)

CRice
CRice

Reputation: 32176

Let the name parameter be a generic that extends keyof T, and then your return type can use that to index T to get the right type. EG:

interface IPerson {
  name: string;
  age: number;
}

declare class MyMap<T> {
  get<K extends keyof T>(name: K): T[K]
}

// Result I need

const map = new MyMap<IPerson>();
map.get("name"); // string
map.get("age"); // number

P.S. Consider naming your class something other than Map, since it will be easily confused with the built-in javascript Map object, and will conflict with TypeScript's built-in types for Map if present.

Upvotes: 2

Related Questions