TypeScript中的类型断言

开发 前端
本文是关于 TypeScript 中的 type assertions 的,它与其他语言中的类型强制转换有相似之处,并通过 as 运算符执行。

[[413386]]

本文是关于 TypeScript 中的 type assertions 的,它与其他语言中的类型强制转换有相似之处,并通过 as 运算符执行。

类型断言

类型断言使我们可以覆盖 TypeScript 为存储位置计算的静态类型,这对于解决类型系统的限制很有用。

类型断言与其他语言中的类型强制转换有相似之处,但是它们不会引发异常,并且在运行时也不做任何事情(它们确实会静态执行一些少量的检查)。

  1. const data: object = ['a', 'b', 'c']; // (A) 
  2.  
  3. // @ts-ignore: Property 'length' does not exist on type 'object'. 
  4. data.length; // (B) 
  5.  
  6. assert.equal( 
  7.   (data as Array<string>).length, 3); // (C) 
  • 在 A 行中,我们把 Array 的类型扩展为 object。
  • 在 B 行中,我们看到此类型不允许访问任何属性。
  • 在 C 行中,我们用类型断言(运算符 as)告诉 TypeScript data 是一个Array。现在就可以访问属性 .length 了。

类型断言是不得已的方法,应尽可能的避免。他们(暂时)删除了静态类型系统为我们提供的安全网。

注意,在 A 行中,我们还覆盖了 TypeScript 的静态类型,不过是通过类型注释完成的。这种覆盖方式比类型声明要安全得多,因为你可以做的事情少得多。TypeScript 的类型必须能够分配给注释的类型。

(1) 类型断言的替代语法

TypeScript 对于类型断言有另一种“尖括号”语法:

  1. <Array<string>>data 

该语法已经过时,并且与 React JSX 代码(在 .tsx 文件中)不兼容。

(2) 示例:声明一个接口

为了访问任意对象 obj 的属性 .name,我们暂时将 obj 的静态类型更改为 Named(A行和B行)。

  1. interface Named { 
  2.   name: string; 
  3. function getName(obj: object): string { 
  4.   if (typeof (obj as Named).name === 'string') { // (A) 
  5.     return (obj as Named).name; // (B) 
  6.   } 
  7.   return '(Unnamed)'; 

(3) 示例:声明索引签名

在以下代码中,我们在行 A 用了类型断言 as Dict ,以便可以访问其推断类型为 object 的值的属性。也就是说,用静态类型 Dict 覆盖了推断的静态类型 object。

  1. type Dict = {[k:string]: any}; 
  2.  
  3. function getPropertyValue(dict: unknown, key: string): any { 
  4.   if (typeof dict === 'object' && dict !== null && key in dict) { 
  5.     // %inferred-type: object 
  6.     dict; 
  7.  
  8.     // @ ts-ignore:元素隐式具有“any”类型,因为 
  9.     // 类型'string'的表达式不能用于索引类型'{}'。 
  10.     // 在类型“ {}”上没有找到参数类型为'string'的索引签名。 
  11.     dict[key]; 
  12.      
  13.     return (dict as Dict)[key]; // (A) 
  14.   } else { 
  15.     throw new Error(); 
  16.   } 

与类型断言相关的构造

(1) 非空断言运算符(后缀 !)

如果值的类型是包含 undefined 或 null 类型的联合,则 non-nullish声明运算符(或 non-null 声明运算符)将从联合中删除这些类型。我们告诉 TypeScript:“这个值不能是 undefined 或 null。”因此,我们可以执行这两个值的类型所阻止的操作,例如:

  1. const theName = 'Jane' as (null | string); 
  2.  
  3. // @ts-ignore: Object is possibly 'null'. 
  4. theName.length; 
  5.  
  6. assert.equal( 
  7.   theName!.length, 4); // OK 

(2) 示例 – Maps: .has() 之后的 .get()

使用 Map 方法 .has() 之后,我们知道 Map 具有给定的键。遗憾的是,.get() 的结果不能反映这一点,这就是为什么我们必须使用 nullish 断言运算符的原因:

  1. function getLength(strMap: Map<string, string>, key: string): number { 
  2.   if (strMap.has(key)) { 
  3.     // We are sure x is not undefined: 
  4.     const value = strMap.get(key)!; // (A) 
  5.     return value.length; 
  6.   } 
  7.   return -1; 

由于 strMap 的值永远不会是 undefined,因此我们可以通过检查 .get() 的结果是否为 undefined 来检测丢失的 Map 条目(A 行):

  1. function getLength(strMap: Map<string, string>, key: string): number { 
  2.   // %inferred-type: string | undefined 
  3.   const value = strMap.get(key); 
  4.   if (value === undefined) { // (A) 
  5.     return -1; 
  6.   } 
  7.  
  8.   // %inferred-type: string 
  9.   value; 
  10.  
  11.   return value.length; 

(3) 定值断言

如果打开 strict 属性初始化,有时需要告诉 TypeScript 我们确实初始化某些属性——即使它认为我们不需要这样做。

这是一个例子,尽管 TypeScript 不应这样做,但它仍会报错:

  1. class Point1 { 
  2.   // @ts-ignore: Property 'x' has no initializer and is not definitely 
  3.   // assigned in the constructor. 
  4.   x: number; 
  5.  
  6.   // @ts-ignore: Property 'y' has no initializer and is not definitely 
  7.   // assigned in the constructor. 
  8.   y: number; 
  9.  
  10.   constructor() { 
  11.     this.initProperties(); 
  12.   } 
  13.   initProperties() { 
  14.     this.x = 0
  15.     this.y = 0
  16.   } 

如果我们在 A 行和 B 行中使用“定值分配断言”(感叹号),则错误会消失:

  1. class Point2 { 
  2.   x!: number; // (A) 
  3.   y!: number; // (B) 
  4.   constructor() { 
  5.     this.initProperties(); 
  6.   } 
  7.   initProperties() { 
  8.     this.x = 0
  9.     this.y = 0
  10.   } 

 

责任编辑:赵宁宁 来源: 前端先锋
相关推荐

2023-10-29 16:18:26

Go接口

2022-04-11 08:42:09

TypeScript子类型定义

2022-08-08 09:00:42

TypeScript映射类型

2020-12-18 11:35:22

TypeScript语言Java

2022-04-10 19:26:07

TypeScript类型语法

2015-07-08 16:00:32

Foundation

2022-02-25 09:06:02

TypeScripnever工具

2023-07-16 23:43:05

Go语言模式

2021-08-18 07:56:05

Typescript类型本质

2022-09-20 14:43:55

TypeScript类型体操

2021-06-09 07:55:19

Typescript类型检查

2022-05-04 09:02:41

TypeScript类型工具

2024-03-20 00:04:46

TypeScriptas const类型断言

2020-09-15 08:35:57

TypeScript JavaScript类型

2022-08-10 09:03:35

TypeScript前端

2019-03-21 09:45:11

TypeScript编程语言Javascript

2022-03-09 20:18:49

TypeScript类型函数

2023-08-15 10:12:11

TypeScript标准库

2021-08-06 06:51:15

TypeScript Any 类型

2020-09-23 09:08:05

typescript
点赞
收藏

51CTO技术栈公众号