When to use the Generic Types

May 12, 2023

Typescript

When to use the Generic Types

Thuta Sann

Thuta Sann

In this section, I will briefly explain about when to use the Generic Types in typescript.


Share This Snippet To :

Generic Types

In this section, I will briefly explain about when to use the Generic Types in typescript.

interface Animal { name: string; } interface Human { firstName: string; lastName: string; } type AnimalOrHuman<T extends Human | Animal> = T extends Human ? { humanName: string } : { animalName: string }; export const getDisplayName = <TItem extends Animal | Human>( item: Animal | Human, ): AnimalOrHuman<TItem> => { if ('name' in item) { return { animalName: item.name, } as AnimalOrHuman<TItem>; } else { return { humanName: `${item.firstName} ${item.lastName}`, } as AnimalOrHuman<TItem>; } };

Cookie

I baked some cookies that you have to accept, if you want to enjoy my portfolio.
In order to gather information and make improvements, I should use some third-party cookies too, Can I?