“This is the 12th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

preface

Previously we introduced the types of TS, but today we will add two: the union type and the cross type

Take a look at the cross type 👇 first

Cross type

A cross type is a combination of multiple types into a single type by using the ampersand symbol

And that means that we can take the types that we talked about earlier, and add them all together as one type

Take an official example 🌰 :

function extend<T.U> (first: T, second: U) :T & U {
    letresult = <T & U>{}; for (let id in first) { (<any>result)[id] = (<any>first)[id]; } for (let id in second) { if (! result.hasOwnProperty(id)) { (<any>result)[id] = (<any>second)[id]; } } return result; } class Person { constructor(public name: string) { } } interface Loggable { log(): void; } class ConsoleLogger implements Loggable { log() { // ... } } var jim = extend(new Person("Jim"), new ConsoleLogger()); var n = jim.name; jim.log();Copy the code

The code above is a simple example of creating mixins, where the return value type is T & U, which is the crossover type

Isn’t it easy?

Now look at union types

The joint type

It’s similar to the crossover type, but different

What is similar is that it also concatenates multiple types with a single symbol as a new type

The difference is:

  • The join symbol used for cross types is&, whereas union types use vertical lines|Separate each type;
  • And they mean different things. A union type means that a value can be of several typesOne of the, such asnumber | stringIndicates that a value can benumberorstring

If a value is a union type, we can access only the members that are common to all types of the union type.

Or take the official example 🌰 :

interface Bird {
    fly();
    layEggs();
}

interface Fish {
    swim();
    layEggs();
}

function getSmallPet() :Fish | Bird {
    // ...
}

let pet = getSmallPet();
pet.layEggs(); // okay
pet.swim();    // errors
Copy the code

The above code, again to verify what was just emphasized above, can only access the common members, so layEggs can access it because it is public, whereas Swim is unique to Fish and therefore cannot!

END

That’s all for this article. If you have any questions, please point out