I have the following code:
interface Person {
name: string;
age: number;
}
class Store<T, K extends keyof T> {
constructor(private obj: T) { }
get(key: K): T[typeof key] {
return this.obj[key];
}
}
const person: Person = {
name: 'John',
age: 99
};
const store = new Store(person);
const value = store.get('name');
value type shows:
const value = store.get('name');
// ^^^^^ value: string | number
How to infer the value type of an object given its key as an argument in a class method?
I want value to be properly typed as string in this case. How to achieve this?