TypeScript中的类型断言

做者:Dr. Axel Rauschmayer

翻译:疯狂的技术宅html

原文:https://2ality.com/2020/06/ty...前端

未经容许严禁转载程序员

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


类型断言

类型断言使咱们能够覆盖 TypeScript 为存储位置计算的静态类型,这对于解决类型系统的限制颇有用。typescript

类型断言与其余语言中的类型强制转换有类似之处,可是它们不会引起异常,而且在运行时也不作任何事情(它们确实会静态执行一些少许的检查)。segmentfault

const data: object = ['a', 'b', 'c']; // (A)

// @ts-ignore: Property 'length' does not exist on type 'object'.
data.length; // (B)

assert.equal(
  (data as Array<string>).length, 3); // (C)
  • 在 A 行中,咱们把 Array 的类型扩展为 object
  • 在 B 行中,咱们看到此类型不容许访问任何属性。
  • 在 C 行中,咱们用类型断言(运算符 as)告诉 TypeScript data 是一个Array。如今就能够访问属性 .length 了。

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

注意,在 A 行中,咱们还覆盖了 TypeScript 的静态类型,不过是经过类型注释完成的。这种覆盖方式比类型声明要安全得多,由于你能够作的事情少得多。 TypeScript 的类型必须可以分配给注释的类型。服务器

类型断言的替代语法

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

<Array<string>>data

该语法已通过时,而且与 React JSX 代码(在 .tsx 文件中)不兼容。多线程

示例:声明一个接口

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

interface Named {
  name: string;
}
function getName(obj: object): string {
  if (typeof (obj as Named).name === 'string') { // (A)
    return (obj as Named).name; // (B)
  }
  return '(Unnamed)';
}

示例:声明索引签名

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

type Dict = {[k:string]: any};

function getPropertyValue(dict: unknown, key: string): any {
  if (typeof dict === 'object' && dict !== null && key in dict) {
    // %inferred-type: object
    dict;

    // @ ts-ignore:元素隐式具备“any”类型,由于
    // 类型'string'的表达式不能用于索引类型'{}'。
    // 在类型“ {}”上没有找到参数类型为'string'的索引签名。
    dict[key];
    
    return (dict as Dict)[key]; // (A)
  } else {
    throw new Error();
  }
}

与类型断言相关的构造

非空断言运算符(后缀 !

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

const theName = 'Jane' as (null | string);

// @ts-ignore: Object is possibly 'null'.
theName.length;

assert.equal(
  theName!.length, 4); // OK

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

使用 Map 方法 .has() 以后,咱们知道 Map 具备给定的键。遗憾的是,.get() 的结果不能反映这一点,这就是为何咱们必须使用 nullish 断言运算符的缘由:

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

因为 strMap 的值永远不会是 undefined,所以咱们能够经过检查 .get() 的结果是否为 undefined 来检测丢失的 Map 条目(A 行):

function getLength(strMap: Map<string, string>, key: string): number {
  // %inferred-type: string | undefined
  const value = strMap.get(key);
  if (value === undefined) { // (A)
    return -1;
  }

  // %inferred-type: string
  value;

  return value.length;
}

定值断言

若是打开 strict 属性初始化,有时须要告诉 TypeScript 咱们确实初始化某些属性——即便它认为咱们不须要这样作。

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

class Point1 {
  // @ts-ignore: Property 'x' has no initializer and is not definitely
  // assigned in the constructor.
  x: number;

  // @ts-ignore: Property 'y' has no initializer and is not definitely
  // assigned in the constructor.
  y: number;

  constructor() {
    this.initProperties();
  }
  initProperties() {
    this.x = 0;
    this.y = 0;
  }
}

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

class Point2 {
  x!: number; // (A)
  y!: number; // (B)
  constructor() {
    this.initProperties();
  }
  initProperties() {
    this.x = 0;
    this.y = 0;
  }
}

本文首发微信公众号:前端先锋

欢迎扫描二维码关注公众号,天天都给你推送新鲜的前端技术文章

欢迎扫描二维码关注公众号,天天都给你推送新鲜的前端技术文章

欢迎继续阅读本专栏其它高赞文章:


相关文章
相关标签/搜索