About union types in TypeScript

In TypeScript, |symbols are used to define union types (Union Types). A union type is an advanced type definition that allows you to define a type as one of many types. This is useful for dealing with variables that may have more than one type.

For example, suppose we have a function that takes one argument, which may be a number or a string. In JavaScript, we cannot explicitly specify the type of this parameter, but in TypeScript, we can use union types to do this:

function logInput(input: string | number) {
    
    
  console.log(input);
}

In the above code, inputthe type of the parameter is defined as string | number, which means it can be a string or a number.

Union types are especially useful because TypeScript checks our code against all possible types in a union type. For example, consider the following code:

function getLength(input: string | number) {
    
    
  return input.length;
}

This code results in an error because numberthe type does not have lengtha property. TypeScript's type checker knows inputthat may be a number, so it won't let us try to access lengththe property.

To handle this situation, we can use type assertions or type guards:

function getLength(input: string | number) {
    
    
  if (typeof input === 'string') {
    
    
    return input.length;
  } else {
    
    
    return input.toString().length;
  }
}

In this example, we first check to see inputif is a string. If it is, we know it has lengththe attribute, so we can safely access it. If inputis not a string, then we know it has to be a number, so we can convert it to a string and get its length.

Union types can also be used with other TypeScript features, such as type aliases and interfaces. For example, we can define a type alias that is a union of two interface types:

interface Cat {
    
    
  type: 'cat';
  breeds: string;
  age: number;
}

interface Dog {
    
    
  type: 'dog';
  breeds: string;
  age: number;
}

type Pet = Cat | Dog;

function printPet(pet: Pet) {
    
    
  console.log(`Type: ${
      
      pet.type}, Breeds: ${
      
      pet.breeds}, Age: ${
      
      pet.age}`);
}

In this example, Petthe type is the union type of Catand Dog. This means that a Petcan be either one Cator one Dog.

Overall, the notation in TypeScript |provides a powerful way to deal with values ​​that may have multiple types. By using union types, we can write more flexible code while still maintaining strong type safety.

Guess you like

Origin blog.csdn.net/i042416/article/details/131949020