I'm writing function that'll return single value from object by key or return empty object if key does not exist.
Code:
//example data:
const obj = {
data: {test: 'word'},
str: 'Hi',
num: 22,
}
const pickOne = <T extends object>(obj: T, key: keyof typeof obj) => ((key in obj) ? obj.key : {})
console.log(pickOne(obj, 'data')) //should print {test: 'word'}
My problem is that I get this error: Property 'key' does not exist on type 'T'.
I'm new to typescript but after reading docs I was sure that keyof typeof would allow any key in obj.
Any help would be appreciated, thanks.
T extends Record<string, unknown>instead ofT extends object. Becauseobjectis very wide type