I'm currently working on a TypeScript function that aims to retrieve a property from an object with the condition that the returned property must extend a certain HasID
interface.
I envision being able to utilize it in this manner:
let obj = {
foo: 123,
bar: {
id: 123
}
};
get(obj, 'foo') // Error
get(obj, 'bar') // All good here
This is what I've come up with so far:
interface HasID {
id: number;
}
interface HasPropertyWithID<K, T extends HasID> {
K: T
}
function get<
T extends HasID,
K extends keyof O,
O extends HasPropertyWithID<K, T>
>(obj: O, key: K): T {
return obj[key]
}
However, the error
'O[K]' is not assignable to type 'T'
is arising. Is there a way to work around this limitation of TypeScript's type system?