TypeScript中的類型斷言

TypeScript中的類型斷言
本文是關於 TypeScript 中的 type assertions 的,它與其餘語言中的類型強制轉換有類似之處,並經過 as 運算符執行。html

類型斷言


類型斷言使咱們能夠覆蓋 TypeScript 爲存儲位置計算的靜態類型,這對於解決類型系統的限制頗有用。typescript

類型斷言與其餘語言中的類型強制轉換有類似之處,可是它們不會引起異常,而且在運行時也不作任何事情(它們確實會靜態執行一些少許的檢查)。安全

1const data: object = ['a', 'b', 'c']; // (A)
2
3// @ts-ignore: Property 'length' does not exist on type 'object'.
4data.length; // (B)
5
6assert.equal(
7  (data as Array<string>).length, 3); // (C)
  • 在 A 行中,咱們把 Array 的類型擴展爲 object。ide

  • 在 B 行中,咱們看到此類型不容許訪問任何屬性。this

  • 在 C 行中,咱們用類型斷言(運算符 as)告訴 TypeScript data 是一個Array。如今就能夠訪問屬性 .length 了。

類型斷言是不得已的方法,應儘量的避免。他們(暫時)刪除了靜態類型系統爲咱們提供的安全網。code

注意,在 A 行中,咱們還覆蓋了 TypeScript 的靜態類型,不過是經過類型註釋完成的。這種覆蓋方式比類型聲明要安全得多,由於你能夠作的事情少得多。TypeScript 的類型必須可以分配給註釋的類型。htm

類型斷言的替代語法


TypeScript 對於類型斷言有另外一種「尖括號」語法:對象

1<Array<string>>data

該語法已通過時,而且與 React JSX 代碼(在 .tsx 文件中)不兼容。blog

示例:聲明一個接口


爲了訪問任意對象 obj 的屬性 .name,咱們暫時將 obj 的靜態類型更改成 Named(A行和B行)。索引

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

示例:聲明索引簽名


在如下代碼中,咱們在行 A 用了類型斷言 as Dict ,以即可以訪問其推斷類型爲 object 的值的屬性。也就是說,用靜態類型 Dict 覆蓋了推斷的靜態類型 object。

1type Dict = {[k:string]: any};
 2
 3function 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  }
17}

與類型斷言相關的構造

非空斷言運算符(後綴 !


若是值的類型是包含 undefined 或 null 類型的聯合,則 non-nullish聲明運算符(或 non-null 聲明運算符)將從聯合中刪除這些類型。咱們告訴 TypeScript:「這個值不能是 undefined 或 null。」所以,咱們能夠執行這兩個值的類型所阻止的操做,例如:

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

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

使用 Map 方法 .has() 以後,咱們知道 Map 具備給定的鍵。遺憾的是,.get() 的結果不能反映這一點,這就是爲何咱們必須使用 nullish 斷言運算符的緣由:

1function 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;
8}

因爲 strMap 的值永遠不會是 undefined,所以咱們能夠經過檢查 .get() 的結果是否爲 undefined 來檢測丟失的 Map 條目(A 行):

1function 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;
12}

定值斷言


若是打開 strict 屬性初始化,有時須要告訴 TypeScript 咱們確實初始化某些屬性——即便它認爲咱們不須要這樣作。

這是一個例子,儘管 TypeScript 不該這樣作,但它仍會報錯:

1class 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  }
17}

若是咱們在 A 行和 B 行中使用「定值分配斷言」(感嘆號),則錯誤會消失:

1class 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  }
11}

原文連接

https://2ality.com/2020/06/type-assertions-typescript.html

相關文章
相關標籤/搜索