类型断言与类型防护

要像使用其他类型一样使用 unknown 类型,你必须先让 unknown 类型的变量转换为某种已知的具体类型的变量。主要有两种方法——类型断言与类型防护。

类型断言的作用是将一种类型断言为另一种类型,并按照断言后的类型使用。类型断言可以使用 as 关键字,也可以使用尖括号语法。建议优先使用 as 关键字,因为在 JSXJavaScript 的一种语法扩展)中仅允许使用 as 关键字。

使用 as 关键字的类型断言示例代码如下。

let a: unknown = 1
let b = (a as number) + 2;           //b的值为3

let c: unknown = [1, 2];
(c as number[]).push(3);             //c的值为[1,2,3]

let d: unknown = { x: "hello" }
console.log((d as { x: string }).x); //输出hello

使用尖括号语法的类型断言示例代码如下。

let a: unknown = 1
let b = <number>a + 2;               //b的值为3

let c: unknown = [1, 2];
(<number[]>c).push(3);               //c的值为[1,2,3]

let d: unknown = { x: "hello" }
console.log((<{ x: string }>d).x);   //输出"hello"

类型防护即首先用 typeofinstanceof 运算符判定类型,或使用 ===(全等运算符,及值与类型完全相等)判定是否完全相等,然后才使用该变量。示例代码如下。

let a: unknown = 1
if (typeof a == "number")
    console.log(a + 2);  //输出3

if (a === 1)
    console.log(a + 4);  //输出5

let b: unknown = [1, 2];
if (b instanceof Array) {
    b.push(3);
    console.log(b);      //输出[1,2,3]
}