Conditional types take generics one step further and allow you to test for a specific condition, based on which the final type will be determined. We will look at how they work on a basic level and then leverage their power to allocate function types dynamically based on the type of their parameters, all without any overloads.
I tried to read on conditional types and nothing made sense... but your video really nailed it down in 3 minutes.. good job!!
Excellent video!!! Can you please help me understand how one would implement getItem() and differentiate between whether id is a number or string?
Anup, That's a good question. Let me see if I can find an answer.
Hi Anup, very good question!
The example I gave above is very useful to consumers of that API.
When implementing it unfortunately, there's a current a limitation of the TS compiler where it can't safely infer whether you're returning the correct value. More details here:
So you will have to use casting:
let itemService: IItemService = {
getItem: <T extends string | number>(id: T) => {
const books: Book[] = [
{ id: "1", tableOfContents: [] },
{ id: "2", tableOfContents: [] }
];
const tvs: Tv[] = [
{ id: 1, diagonal: 40 },
{ id: 2, diagonal: 50 }
];
if (typeof id === "string") {
return <T extends string ? Book : Tv>books.find(book => book.id === id)!;
} else {
return <T extends string ? Book : Tv>tvs.find(tv => tv.id === id)!;
}
}
};