Explain type protection in typescript

Time:2022-5-8
catalogue
  • summary
  • Type Asserts
  • In syntax
  • Instanceof syntax
  • Typeof syntax
  • summary

summary

When using union types in typescript, you often encounter this embarrassing situation:

interface Bird {
  	//Unique method
    fly();
  	//Common method
    layEggs();
}

interface Fish {
  	//Unique method
    swim();
  	//Common method
    layEggs();
}

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

let pet = getSmallPet();
pet. layEggs(); //  normal
pet. swim();    //  TS error

As shown above, the getsmallpet function can return both fish type objects and bird type objects. Because the returned object type is uncertain, everything is normal when using the methods common to the union type object, but when using the methods unique to the union type object, TS will report an error.

So how to solve this problem? Of course, the crudest method is to convert the union type to any, but this method is not worth advocating. After all, we write typescript instead of anyscript.

At this time, we use today’s protagonist – type protection, which can solve this problem perfectly.

Kong Yiji said that there are four ways to write fennel beans. Similarly, there are four ways to realize type protection.

Type Asserts

Type assertion is the most commonly used type protection method, that is, directly specifying the type. Since most of the types recognized in typescript are calculated by the automatic type calculation of typescript, the problem mentioned above will arise, that is, typescript does not know what the specific object type is, so it is uncertain whether there are unique methods of joint types.

When using type assertion to directly specify a type, it is equivalent to that you let typescript turn on God mode, and you can directly know that the specific type is the one in the union type. At this time, using the unique method of the object conforms to the inference of typescript.

interface Bird {
  //Unique method
  fly();
  //Common method
  layEggs();
}

interface Fish {
  //Unique method
  swim();
  //Common method
  layEggs();
}

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

let pet = getSmallPet();
pet. layEggs(); //  normal
//Judge by duck type
if ((pet as Bird).fly) {
  //Type assertion
  (pet as Bird).fly()
} else {
  //Type assertion
  (pet as Fish).swim()
}

If the generic type of assertion is not enough, you can also use the generic type of assertion:

let pet = getSmallPet();
pet. layEggs(); //  normal
//Judge by duck type
if ((<Bird>pet).fly) {
  (<Bird>pet).fly()
} else {
  (<Fish>pet).swim()
}

Tips: Tips: although it seems high-end to use generic like writing for type assertion, it is recommended to use the as method for type assertion for the sake of unity due to the ambiguity of syntax in TSX.

In syntax

In JS, we often use in syntax to judge whether the specified attribute is in the specified object or its prototype chain.

Similarly, in typescript, we can confirm the object type through this method.

interface Bird {
  //Unique method
  fly();
  //Common method
  layEggs();
}

interface Fish {
  //Unique method
  swim();
  //Common method
  layEggs();
}

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

let pet = getSmallPet();
pet. layEggs(); //  normal
//Type protection using in syntax
if ('fly' in pet) {
  pet.fly()
} else {
  pet.swim()
}

The principle is the same as that of type assertion, which is to guide the type inference of typescript and determine the object type.

Instanceof syntax

Instanceof syntax comes in handy when the union type uses class instead of interface. Different class types can be distinguished through instanceof syntax.

class Bird {
  //Unique method
  fly() {};
  //Common method
  layEggs() {};
}

class Fish {
  //Unique method
  swim() {};
  //Common method
  layEggs() {};
}

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

let pet = getSmallPet();
pet. layEggs(); //  normal
//Using in syntax
if (pet instanceof Bird) {
  pet.fly()
} else {
  pet.swim()
}

Typeof syntax

Typeof syntax is different from in syntax and instanceof syntax. In syntax and instanceof syntax are used to guide type inference and infer different object types, while typeof syntax is often used to infer basic types (or combine basic types and object types).

In short, typeof can be used when it can distinguish between different types in a union type.


function getSmallPet(): number | string {
  // ...
}

let pet = getSmallPet();
if (typeof pet === 'number') {
  pet++
} else {
  pet = Number(pet) + 1
}

summary

Just as the essence of the four writing methods of fennel bean is still fennel bean, the essence of the four writing methods of type protection is the same, that is, guiding type inference in typescript to change the multiple-choice question of type inference into single-choice question, which is the essence of type protection.

The above is the detailed content of typescript type protection. For more information about typescript type protection, please pay attention to other related articles of developeppaer!

Recommended Today

The multi architecture image creation guide has arrived, please check it!

Summary:Using multi architecture image allows docker to pull the corresponding image according to the system architecture. The deployment script of services can use the same configuration between systems with different architectures, reducing the service configuration and improving the consistency of services between different system architectures. background Because kubernetes cluster supports the system of AMD64 and […]