Union Types

Use | separating each type.

Note: Only the common properties or methods of all properties of the union type can be accessed when the union type is uncertain. Ts emits an error when accessing a unique type. So, how do you do type protection?

  1. Use type assertions.
interface A {
  name: 'g'.age: 21
}
interface B {
  name: 'j'.sex: 'male'
}
function func(arg: A | B) {
  if(arg.name === 'g') { // Use common attributes to judge logically
    console.log((arg as A).age)
  } else {
    console.log((arg as B).sex)
  }
}
Copy the code
  1. useingrammar
function func2(arg: A | B) {
  if('age' in arg) {
    console.log(arg.age)
  } else {
    console.log(arg.sex)
  }
}
Copy the code
  1. usetypeof
  2. Use the instanceof

When it is clear which type it is, the TS error can be removed

Enumerated type

Use enum keyword definition.

    enum Name {
        A,
        B
    }
Copy the code
  • By default, enumerations start at 0. This can be modified by manual assignment. Subsequent elements that are not assigned are incremented.
  • Enumeration types can be taken in reverse:Name.A <==> Name[0]

  • Note: ts does not know if unassigned elements (whose values are incremented) are the same as assigned elements. And the following element overwrites the preceding element

The generic

The function of generic

    function func<T> (arg: T) {... }Copy the code

Kind of generic

    class cls<T> {}Copy the code

Generics are primarily the property of defining functions, classes, or interfaces without specifying a specific type, and specifying the type when used. You can use extends to constrain generics! For example, constraint specifies that the generic type contains the name attribute

    interface HasName { // 
        name: string
    }
    function func<T extends HasName> {... }Copy the code

Another example is the number or string constraint for a generic type

    function func<T extends number | string> () {... }Copy the code

Use keyof to constrain generics to take only certain values

What are the similarities between interfaces and tuples?

What is the difference between an interface and a type alias?

What are the different forms of functions?