ed'
ed'

Reputation: 1895

Getting type of property in type extension

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

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

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

Related Questions