Reputation: 1895
function extractIdFromObject<T extends { id: U }, U>(item: T) {
return item.id;
}
const x = extractIdFromObject({ id: 1 });
const y = extractIdFromObject({ id: "1" });
const z = extractIdFromObject({ id: {} });
I wrote the function above, which given an object that has the property id
, will return the value of id
.
Whilst the above will run just fine, the TS engine infers x
, y
and z
to be {}
.
How must I alter my type in order to receive correct type information for U
(item.id
)?
Upvotes: 1
Views: 68
Reputation: 249476
Getting Typescript to infer one type parameter based on another doesn't usually work. The simplest solution in this case is to use a type query.
function extractIdFromObject<T extends { id: any }>(item: T): T['id']{
return item.id;
}
const x = extractIdFromObject({ id: 1 });
const y = extractIdFromObject({ id: "1" });
const z = extractIdFromObject({ id: {} });
Upvotes: 2