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 !

![[C语言]用结构体把平均分和低于等于平均分的学生数据输出](/img/c4/263301a22b61c86a3e0df6ad2596f1.png)
![[FAQs for novices on the road] about project management](/img/14/68f5e4cead5573fc932350d8d9b06e.png)


![Spring 2021 daily question [week3 not finished]](/img/a4/72f2235d014613d26be0fc3524d236.jpg)
![Codeworks round 481 (Div. 3) [done]](/img/60/01ed6180ccc4c99fe361d493525018.jpg)

![[untitled]](/img/ab/04beacfc7975cc3c54399447aa5027.png)
