Union type and type protection in TypeScript

Joint type and type protection

1. Joint type

When one of our methods can accept multiple types of parameters (parameter), then the union type is used at this time .

class Student {
    name: string;
    jiaozuoye() { };
}
class Teacher {
    name: string;
    gaizuoye() { };
}
function f(parameter: Student | Teacher) { }

2. Type protection

However, there is another problem that comes with the union type. If there are two different methods in Student and Teacher, how can parameters of different types determine whether there is a special method that inherits the type? To solve this problem, we introduced the concept of type protection .

as syntax

As is also called type assertion. As is equivalent to artificial judgment. For example, a person's name (name attribute) is called "student", then we judge that he is a student and let him call the student's method jiaozuoye(). The specific operation is as follows.

function f(parameter: Student | Teacher) {
    if(parameter.name == "学生"){
        (parameter as Student).jiaozuoye();
    }
}

in syntax

The in grammar is easier to understand. For example, the difference between our Student and Teacher lies in the difference between the method of handing in homework and changing the homework. If the parameter has the function of handing in homework, then we judge him as Student, otherwise judge him as Teacher. When you can use in syntax.

function f(parameter: Student | Teacher) {
    if("jiaozuoye" in parameter){
        parameter.jiaozuoye();
    }else{
        parameter.gaizuoye();
    }
}

typeof syntax

In the above example, the parameters are all custom types. What is our type protection strategy for common types? Give a new example

function f(parameter1: string | number, parameter2: string | number) {
//使用typeof进行类型判断
  if (typeof parameter1 === "string" || typeof parameter2 === "string") {
  //字符串拼接
    return `${first}${second}`;
  }
  return first + second;
}

instanceof syntax

The syntax of instanceof and typeof is very similar, but instanceof can only be used to protect the class .

// 我们先定义一个类,作为我们类型保护的基础
class NumberObj {
    count: number;
}
// 实现一个相加的方法
function f(first: object | NumberObj, second: object | NumberObj) {
    // 运用instanceof语句对类型进行判断
    if (first instanceof NumberObj && second instanceof NumberObj) {
        return first.count + second.count;
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_43592084/article/details/109542522