1. 程式人生 > 其它 >[Typescript] When to use generic type?

[Typescript] When to use generic type?

Let's see when we have following code:

interface Animal {
  name: string;
}

interface Human {
  firstName: string;
  lastName: string;
}

const getDisplayName = (
  item: Animal | Human
): {displayName: string} => {
  if ('name' in item) {
    return {
      displayName: item.name
    }
  } else
{ return { displayName: `${item.firstName} ${item.lastName}` } } }

The function getDisplayName gets all the information it needs to determine what's the return type. In this case, generic type is not necessary.

 

But in the following code, without generic type, it cannot determine what is the actual return type.

interface Animal {
  name: string;
}

interface Human {
  firstName: string;
  lastName: string;
}

const getDisplayName = (
  item: Animal | Human
): { animalName: string } | { humanName: string } => {
  if ("name" in item) {
    return {
      animalName: item.name,
    };
  } else {
    return
{ humanName: `${item.firstName} ${item.lastName}`, }; } }; const name1 = getDisplayName({ name: "cat" }); const name2 = getDisplayName({ firstName: "joe", lastName: "smith" });

Both name1 and name2 are the union type.

 

Now let's switch to generic types:

const getDisplayName = <T extends Animal | Human>(
  item: T
): T extends Animal ? { animalName: string } : { humanName: string } => {
  if ("name" in item) {
    return { animalName: item.name };
  } else {
    return { humanName: `${item.firstName} ${item.lastName}` };
  }
};

const name1 = getDisplayName({ name: "cat" });
const name2 = getDisplayName({ firstName: "joe", lastName: "smith" });