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>;
}
};