Quick Index of articles:

TypeScript Quick Start Tutorial (1) basic types and variable declarations (2) Object-Oriented knowledge (interfaces, Classes, abstract Classes Join & Cross types & Type Protection

Union types and cross types are actually a very common case in life.

  • Cucumber? Is it a fruit or a vegetable?
  • Are tomatoes a fruit or a vegetable?
  • What about fruit cucumbers?

In fact, if we just look at cucumbers and tomatoes, they can be regarded as fruits and vegetables, depending on the scene. When I cook, they are vegetables, and when I eat them raw, they are fruits.

Based on the above knowledge, we can understand:

  • A union type, which can be of type A or B, in pseudocode, isA | B
  • Cross type, whose type contains characteristics of A and characteristics of B, in pseudo-code terms, isA & B

According to the above analysis, we first define a fruit and a vegetable interface for easy use.

Fruit interface

interface Fruits{

    /** * name */
    name: string

    /** * eat raw */
    eatRawFood(): void
}
Copy the code

Vegetables interface

interface Vegetables{

    /** * name */
    name: string

    /** * cooking */
    cooking() : void
}
Copy the code

1. Association type

For example, 🍅, I can eat it as a fruit and cook it as a vegetable. In this case, it is not possible to define a single determinate type. So he can use the joint type (A | B) definition:

function eatTomatoType(type: Fruits | Vegetables) {
	/ / the method body
}
Copy the code

Is it perfect? You think it’s all right?

So the problem comes again ~ 😄, discover I begin three reason three gas.

For example, I now have a 🍅, I think how to plan to eat?

function eatTomatoType(type: Fruits | Vegetables) {
    console.log(type.name);
   	type.cooking() //error
   	type.eatRawFood()  //error
}
Copy the code

Suppose I haven’t figured out how to eat it yet? The 🍅 attribute has not been set yet, I find that it is impossible to decide which method to use to eat ~ when I return to the program, I find that the two methods type.cooking() and type.eatrawfood () cannot be called properly. Because it can be both fruit and vegetable, the program is in a dilemma.

This is where this type of protection comes in. The primary purpose of type protection is to help us determine an appropriate mode of operation. Type protection is a process of thinking ~

Take a closer look at the code code

function eatTomatoType(type: Fruits | Vegetables) {
    console.log(type.name);
    / / type "Fruits | the Vegetables" there is no attribute "cooking". Type 'Fruits' has no attribute' cooking '.
    // type.cooking()   
    if('eatRawFood' in type) {// If type has the eatRowFood method, it means fruit
        (type as Fruits).eatRawFood()
    } else{(type as Vegetables).cooking
    }
}
Copy the code

Here a judgment is used, ‘eatRawFood’ in type is to determine whether the current type contains the eatRawFood method. If the current method of choice is to eat raw, it is the type of fruit we defined earlier.

class Tomato implements Fruits{
    
    name: string = '🍅';
    eatRawFood(): void {
        console.log(`The ${this.name}It can be eaten raw);
    }

}
eatTomatoType(new Tomato())
Copy the code

It will eventually print out

🍅 🍅 can be eaten rawCopy the code

2. Cross types

We still use cucumber as an example. Ordinary cucumbers may taste very ordinary when eaten directly. Now, in order to make cucumbers both delicious to eat raw and delicious to cook, the Academy of Agricultural Sciences has researched new varieties and fruit cucumbers have emerged

At this point the fruit cucumber, if the type is expressed, the pseudocode might be cucumber & fruit.

class SuperMarket implements Fruits.Vegetables{
    
    name: string = '🥒 is in the supermarket. ';

    cooking(): void {
       console.log(`The ${this.name}, can buy cooking! `);
    }
    
    eatRawFood(): void {
        console.log(`The ${this.name}Can be bought and eaten raw! `); }}let shoppingCart: Fruits & Vegetables = new SuperMarket();

shoppingCart.cooking()
shoppingCart.eatRawFood()
Copy the code

Well, now the newly developed fruit cucumber is on the market, and the supermarket’s vegetable and fruit counters are on the shelves. When you buy it back, you can either cook it or eat it raw.

Of course, this example is a little farfetched, so just understand the question.

3. Type protection

In fact, type protection has been used above, the following is a common type protection method.

  • In type protection

In is used to determine whether it belongs to a class

'cooking' in Vegetables
Copy the code
  • Typeof type protection

Typeof is used to compare type attribution

cooking typeof Function
Copy the code
  • Instanceof protection

Instanceof is mainly used to compare objects

a instanceof A  // Determine the ownership of the object
Copy the code
  • Custom type protection

Custom type protection is a condition that you define yourself.

// Your condition is as follows
A && B // It is a safe type only if the following conditions are met
Copy the code

Feel everybody big guy see here, this ~ salute