返回

TypeScript 演化史 - 10:更好的空值检查和混合类型

前端

空值检查

在 TypeScript 2.2 之前,空值检查是通过在类型后加上一个问号(?)来实现的,例如:

let myVariable: string | null;

这意味着 myVariable 变量可以是字符串类型也可以是空值。如果我们尝试对 myVariable 进行操作,而没有首先检查它是否为 nullundefined,那么就会出现错误。

为了解决这个问题,TypeScript 2.2 引入了更加严格的空值检查。现在,如果我们尝试对一个可能为 nullundefined 的变量进行操作,编译器会自动报错。例如:

let myVariable: string | null;

// 编译器报错:Argument of type 'string | null' is not assignable to parameter of type 'string'.
console.log(myVariable.toUpperCase());

为了避免编译器报错,我们可以在使用 myVariable 之前,先检查它是否为 nullundefined。例如:

let myVariable: string | null;

if (myVariable !== null && myVariable !== undefined) {
  console.log(myVariable.toUpperCase());
}

混合类型

在 TypeScript 2.2 之前,我们只能为变量分配一种类型。例如:

let myVariable: string;

这意味着 myVariable 变量只能是字符串类型。如果我们尝试为 myVariable 分配其他类型的值,那么就会出现错误。

为了解决这个问题,TypeScript 2.2 引入了混合类型。混合类型允许您为相同变量分配不同类型的值。例如:

let myVariable: string | number;

这意味着 myVariable 变量可以是字符串类型也可以是数字类型。我们可以根据不同的情况,为 myVariable 分配不同的类型的值。例如:

let myVariable: string | number;

if (condition) {
  myVariable = "Hello world!";
} else {
  myVariable = 123;
}

console.log(myVariable); // 输出 "Hello world!" 或 123

总结

TypeScript 2.2 中的空值检查和混合类型,是 TypeScript 语言发展史上的两个重要里程碑。这两个特性使得 TypeScript 更加强大和灵活,并使开发人员能够编写出更加可靠和健壮的代码。