0

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
2
  • Your map isn't well-defined. It should be Map<string, IPerson>. Commented Oct 11, 2018 at 20:56
  • In my example Map is my own class. It's not standard Map class. It can contains only Keys like keyof T, and each Value has type defined in incoming object type and depending of Key Commented Oct 11, 2018 at 21:04

1 Answer 1

2

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.

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

1 Comment

Thank you very much! It does what I need

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.