成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

五種在 TypeScript 中使用類型保護的方法

開發 前端
類型保護是一個執行運行時檢查的表達式,以保證某個范圍內的類型。類型保護的一個典型應用場景是縮小聯合類型的類型范圍。這是為了保證類型安全,即在運行時安全地訪問特定類型對象中的特定屬性或方法。

類型保護是一個執行運行時檢查的表達式,以保證某個范圍內的類型。類型保護的一個典型應用場景是縮小聯合類型的類型范圍。這是為了保證類型安全,即在運行時安全地訪問特定類型對象中的特定屬性或方法。

在這篇文章中,我將介紹 5 種實現類型保護的方法。

01、typeof 類型保護

首先我們來介紹一下比較常見的typeof類型防護。typeof 運算符可以在運行時獲取對象的類型,該運算符返回以下可能的值:

  • "string"
  • "number"
  • "bigint"
  • "boolean"
  • "symbol"
  • "undefined"
  • "object"
  • "function"

因此使用 typeof 運算符,我們可以在運行時獲取變量的實際類型。舉個例子:

function printId(id: string | number) {
  if (typeof id === "string") {
    console.log(`ID: ${id.toUpperCase()}`);
  } else if (typeof id === "number") {
    console.log(`ID: ${id}`);
  }
}

在上面的代碼中,我們定義了一個 printId 函數,它包含一個 id 參數,其類型為字符串 | 數字聯合類型。

在函數體中,我們使用 typeof 運算符來確定參數的實際類型。如果id參數是字符串類型,我們會將其值轉換為大寫后再輸出。

那么為什么要使用 typeof 運算符來縮小 id 參數的類型呢?主要原因是為了保證運行時的類型安全。例如,當id參數的類型是數字類型時,但是我們調用id.toUpperCase()方法,就會拋出運行時異常。

在支持 TypeScript IntelliSense 的編輯器中,當您訪問 id 參數的某些屬性時,只能訪問字符串和數字類型的公共屬性。具體如下圖所示:

02、instanceof 類型守衛

雖然typeof運算符可以區分不同的類型,但如果我們想判斷一個對象是否是某個類的實例,從而安全地訪問該實例上特有的屬性或方法,那么typeof運算符就無能為力了。

對于這個需求,我們可以使用instanceof運算符。再次,我們舉一個具體的例子:

class Shape {
  constructor(public id: string) {}
}


class Circle extends Shape {
  constructor(
    public id: string, 
    public radius: number) {
   super(id);
  }
}


class Square extends Shape {
  constructor(
    public id: string, 
    public sideLength: number) {
      super(id);
  }
}

在上面的代碼中,我們定義了一個Shape類,并基于它創建了兩個子類。接下來,我們定義一個 printShapeInfo 函數來打印有關不同形狀的信息:

function printShapeInfo(shape: Shape) {
  if (shape instanceof Circle) {
    console.log(`Circle's radius is: ${shape.radius}`);
  } else if (shape instanceof Square) {
    console.log(`Square's sideLength is: ${shape.sideLength}`);
  }
}

在printShapeInfo函數體中,我們使用instanceof運算符來縮小形狀參數的類型,從而輸出不同形狀的信息。在 if...else if 分支之外,我們只能訪問 Circle 對象和 Square 對象共有的 id 屬性。

03、in type guards

對于前面使用instanceof運算符實現類型保護的示例,我們還可以使用接口的形式來描述Shape、Circle和Square類型。

interface Shape {
  id: string;
}


interface Circle extends Shape {
  radius: number;
}


interface Square extends Shape {
  sideLength: number;
}

由于TypeScript接口定義的類型在編譯后并不會生成對應的類型,因此我們無法在運行時使用instanceof運算符進行類型檢測。要實現printShapeInfo函數的功能,我們可以使用in運算符,具體實現如下:

function printShapeInfo(shape: Shape) {
  if ("radius" in shape) {
    console.log(`Circle's radius is: ${shape.radius}`);
  } else if ("sideLength" in shape) {
    console.log(`Square's sideLength is: ${shape.sideLength}`);
  }
}

除了上述方法之外,我們還可以使用可判別聯合類型來表示Shape類型:

type Circle = {
  id: string;
  type: "circle";
  radius: number;
};


type Square = {
  id: string;
  type: "square";
  sideLength: number;
};


type Shape = Circle | Square;

在Circle和Square類型中,type屬性的類型是字符串文字類型,用于區分不同的形狀,稱為可區分屬性。對于判別聯合類型,結合switch…case語句,我們還可以實現printShapeInfo函數對應的功能。

function printShapeInfo(shape: Shape) {
  switch (shape.type) {
    case "circle":
      console.log(`Circle's radius is: ${shape.radius}`);
      break;
    case "square":
      console.log(`Square's sideLength is: ${shape.sideLength}`);
      break;
    default:
      console.log("Unknown shape");
  }
}

介紹完如何使用常見的 typeof、instanceof 和 in 運算符實現類型保護之后,我們來介紹一下如何定義用戶自定義的類型保護。

04、用戶定義的類型保護

為了演示用戶定義的類型保護,讓我們重新定義 3 種類型:

interface Shape {
  id: string;
}


interface Circle extends Shape {
  radius: number;
}


interface Square extends Shape {
  sideLength: number;
}

定義完Shape相關的類型后,我們來定義用戶自定義的類型保護函數:

function isCircle(shape: Shape): shape is Circle {
  return "radius" in shape;
}


function isSquare(shape: Shape): shape is Square {
  return "sideLength" in shape;
}

與普通函數相比,自定義類型保護函數返回類型謂詞。上面代碼中的 shape is Circle 就是所謂的類型謂詞。謂詞采用parameterName is Type 的形式,其中parameterName 必須是當前函數簽名中的參數名稱。

這樣就可以理解isCircle用戶自定義類型保護函數的作用了。如果函數返回值為true,則shape參數的類型為Circle類型。

現在我們有了 isCircle 和 isSquare 函數,我們可以在 printShapeInfo 函數中使用它們,如下所示:

function printShapeInfo(shape: Shape) {
  if (isCircle(shape)) {
    console.log(`Circle's radius is: ${shape.radius}`);
  } else if (isSquare(shape)) {
    console.log(`Square's sideLength is: ${shape.sideLength}`);
  }
}

05、相等縮小類型防護

除了前面描述的 4 種類型保護方法之外,TypeScript 還支持使用 if/switch 語句和相等檢查,例如 ===、!===、== 和 != 運算符來縮小變量的類型。

function printValues(a: string | number, b: string | string[]) {
  if (a === b) {
    console.log(a.toUpperCase()); // (parameter) a: string
    console.log(b.toUpperCase()); // (parameter) b: string
  } else {
    console.log(a); // (parameter) a: string | number
    console.log(b); // (parameter) b: string | string[]
  }
}

上面的代碼中,printValues函數支持a和b 2個參數,并且它們的類型都是聯合類型。當a===b表達式的計算結果為true時,參數a和b的類型將縮小為字符串類型。當然,使用!==運算符也可以用來實現類型縮小。

function printValues2(a: string | number, b: string | string[]) {
  if (a !== b) {
    console.log(a); // (parameter) a: string | number
    console.log(b); // (parameter) b: string | string[]
  } else {
    console.log(a.toLowerCase()); // (parameter) a: string
    console.log(b.toLowerCase()); // (parameter) b: string
  }
}

這就是關于 TypeScript 類型防護的全部內容。

總結

以上就是我今天想與你分享的5個TS的知識技能,希望對你有所幫助。

責任編輯:華軒 來源: web前端開發
相關推薦

2010-07-27 13:05:12

Flex

2025-01-20 00:13:19

TypeScript操作符數據類型

2023-09-27 10:19:37

類型video函數

2021-09-14 08:00:00

云計算機器ID技術

2021-08-27 16:26:11

敏感數據

2021-03-05 10:17:32

保護組織勒索軟件網絡安全

2023-10-20 10:17:23

2025-03-03 08:06:39

DeepSeek方法工具

2020-06-18 10:26:43

JavaScript開發技術

2013-08-26 09:51:57

2023-11-21 15:23:15

JavaScript工具

2022-08-30 20:00:37

零信任Linkerd

2020-06-04 08:17:44

JavaScript延展操作運算符開發

2022-10-11 16:53:22

GitLinux

2011-05-18 14:10:18

敏感數據安全數據泄漏

2023-05-05 06:56:13

2023-05-04 07:09:08

2023-05-09 17:59:03

2022-06-10 08:01:17

ReduxReact

2023-04-26 15:17:33

Vue 3開發前端
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 国产高清视频在线 | 欧美日韩一区二区电影 | 国产精品永久免费 | 人人干视频在线 | av香蕉 | 国产我和子的乱视频网站 | 亚洲精品在线免费观看视频 | 中文字幕一区二区三区在线视频 | 久国久产久精永久网页 | 日本精品视频一区二区 | 亚洲精品电影网在线观看 | 特黄特色大片免费视频观看 | 美女二区 | 亚洲久草 | 亚洲精品播放 | 午夜男人天堂 | 亚洲高清在线播放 | 神马久久av | 麻豆久久精品 | 欧美日韩国产在线 | 一级黄色夫妻生活 | 成人精品鲁一区一区二区 | 99精品久久久久久久 | 亚洲精品www| 天天插天天操 | 亚洲国产成人精品女人久久久 | 91在线精品一区二区 | 日本高清视频在线播放 | 日本免费黄色 | 亚洲色欲色欲www | 一区二区不卡高清 | 国产精品一区二区视频 | 国产精品一区二区三区四区五区 | 天天干狠狠| 国产成人精品综合 | 天天插天天干 | 超碰人人人人 | 成人三级视频 | www.五月天婷婷 | 精品欧美乱码久久久久久1区2区 | 91精品国产91久久久久久 |