当前位置:网站首页>System learning typescript (V) - joint type

System learning typescript (V) - joint type

2022-06-11 18:15:00 Programming samadhi

Preface

In the preliminary study of TypeScript After the variable declaration of , I love its static type checking function , But also found a problem : In normal development , The type of a variable may sometimes not be limited to number perhaps string One of the , There may be two types or more , such as :

// index.js
let res;
if(userInfo.age && userInfo.age > 12){
    res = userInfo.age;
}else{
    res = userInfo.name;
}

In the above example res The type could be number, It could be string.

How to limit res The type of , Let it meet at the same time number and string The type of inspection ? This involves what we are going to learn today TypeScript Another type declaration of —— Joint type .

About union types

Literally , So-called “ Joint type ” In fact, it is a combination of many types , That is, not just one type .

Joint type (Union Types) You can go through the pipes (|) Set multiple types of variables , The assignment can be made according to the type of setting .

The basic grammar is as follows :

let tag:Type1|Type2|Type3 

It uses “|” The three separated types represent variables tag The range of types that can be assigned .

Be careful : For variables with union type specified , The type of its value must be only one contained in the union type , If you take a type value other than the union type , Errors will be reported during compilation .

Variables that specify the union type can be given any type value in the union type during operation .

Examples of practical use

The following are examples of several practical applications of joint types .

Declare variables

let res: number | string;  //  Union type declaration 
if (userInfo.age > 12) {
    res = userInfo.age;
} else {
    res = userInfo.name;
}
return res;

In the previous example res Can only be assigned to number Type or string type , Assigning other types will result in an error .

Function arguments

We can also use union types in function parameters to control the expected types of parameters :

function sayRes(res: number | string){
    console.log(res);
}

sayRes(true); // Error:  type “boolean” Argument to cannot be assigned to type “string | number” Parameters of .

Union type array

For arrays that may consist of different single type elements, declare , We can also use union types to declare .

let arr5: number[] | string[];
arr5[0] = true; // Error:  You can't type “boolean” Assign to type “string | number”.

Expanding knowledge

Data for union type , Mainly expand the following points .

Only common properties or methods can be accessed

In general , The union type is used because the type of the final value of the variable cannot be determined .

For variables or parameters of union type , If you can't determine its specific type , Only properties or methods common to all types in a union type can be accessed , If you access a property or method unique to a type , There will be errors .

function sayRes(res: number | string) {
    if (res.length > 0) { // Error:  type “number” Property does not exist on “length”.
    }
}

When res by number Type , It doesn't exist .length Attribute , So there's an error .

In the following example , because .toString() yes number and string Methods common to types , So it can be compiled normally :

function sayRes(res: number | string) {
    if (res.toString() === "12") {
    }
}

Type inference

For union type variables , After assignment, the type of the variable will be inferred according to the type of the value .

let res :number | string;
res = " The samadhi of programming ";
console.log(res.length);
res = 12;
console.log(res.length);  // Error:  type “number” Property does not exist on “length”.

In giving res The assignment is 12 after ,TypeScript infer res The type of number,number Type does not exist .length attribute , So wrong reporting .

summary

That's all TypeScript Knowledge of joint types , In summary :

  • The union type contains all possible types of variables ;
  • Assign a value to a union type variable other than the union type , There will be errors ;
  • Before the final type of the union type variable cannot be determined , Only properties and methods common to union types can be accessed .

~

~ The end of this paper , Thank you for reading !

~

Learn interesting knowledge , Make interesting friends , Create interesting souls !

Hello everyone , I am a 〖 The samadhi of programming 〗 The author of Hermit King , My official account is 『 The samadhi of programming 』, Welcome to your attention , I hope you can give me more advice !

原网站

版权声明
本文为[Programming samadhi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203011841149864.html