头图

foreword

After initially learning TypeScript's variable declaration, I can't put it down to its static type checking function, but I also found a problem: in normal development, the type of a variable may not be limited to only one of number or string. 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;
}

The res type in the above example may be number or string.

How to restrict the type of res so that it can satisfy the type checking of number and string at the same time? This involves another type declaration of TypeScript that we are going to learn today - union types.

About union types

Literally, the so-called "joint type" is actually a combination of multiple types, that is, not just one type.

Union Types can set multiple types to variables through pipes (|).

The basic syntax is as follows:

let tag:Type1|Type2|Type3 

The three types separated by "|" represent the range of types to which the variable tag can be assigned.

Note: For a variable with a specified union type, the value type must only be one of the types included in the union type. If a type value other than the union type is taken, an error will be reported during compilation.

A variable with a union type specified can be assigned a value of any type in the union type at runtime.

Practical use example

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

declare variable

let res: number | string;  // 联合类型声明
if (userInfo.age > 12) {
    res = userInfo.age;
} else {
    res = userInfo.name;
}
return res;

The res in the above example can only be assigned to number type or string type, and assigning other types will result in an error.

function parameter

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

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

sayRes(true); // Error: 类型“boolean”的参数不能赋给类型“string | number”的参数。

union type array

For array declarations that may consist of elements of different single types, we can also declare them using union types.

let arr5: number[] | string[];
arr5[0] = true; // Error: 不能将类型“boolean”分配给类型“string | number”。

expand knowledge

For the data of the joint type, the following points are mainly extended.

Only public properties or methods can be accessed

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

For a variable or parameter of a union type, if the specific type cannot be determined, only the properties or methods common to all types in the union type can be accessed. If an attribute or method unique to a certain type is accessed, an error will be reported.

function sayRes(res: number | string) {
    if (res.length > 0) { // Error: 类型“number”上不存在属性“length”。
    }
}

When res is of number type, there is no .length attribute, so an error will be reported.

In the following example, because .toString() is a method shared by the number and string types, it can be compiled normally:

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

type inference

For union-typed variables, the variable's type is inferred from the value's type after assignment.

let res :number | string;
res = "编程三昧";
console.log(res.length);
res = 12;
console.log(res.length);  // Error: 类型“number”上不存在属性“length”。

After assigning a value of 12 to res, TypeScript infers that the type of res is number, and there is no .length property for the number type, so an error is reported.

Summarize

The above is the relevant knowledge of TypeScript union types, summed up as follows:

  • Union types contain all possible types of variables;
  • Assigning a value of a union type variable to a value other than the union type will result in an error;
  • Only properties and methods common to union types can be accessed until the final type of the union type variable cannot be determined.

~

~ This article is over, thanks for reading!

~

Learn interesting knowledge, meet interesting friends, and shape interesting souls!

Hello everyone, I am , the author of 〖 Programming Samadhi 〗. My is " Programming Samadhi ".


编程三昧
54 声望10 粉丝

学习有趣的知识,交识有趣的朋友,造就有趣的灵魂!