I would like to be able to have a simple get function defined as: const get = (key, obj) => obj[key]; I'm struggling to annotate it properly so that it properly infers that get("x", {"x": 2}) is a number. So far I have:
function get<K extends PropertyKey, T extends object>(key: K, obj: T): K extends keyof T ? T[K] : undefined {
const hasKey = (obj: T, key: PropertyKey): key is keyof T => key in obj;
if (hasKey(obj, key)) return obj[key];
return undefined;
}
But I have 2 errors:
- Type 'T[K & keyof T]' is not assignable to type 'K extends keyof T ? T[K] : undefined'.
- Type 'undefined' is not assignable to type 'K extends keyof T ? T[K] : undefined'
How should I be able to fix them and could you help me to understand this error messages? Here is a link to the playground.
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.