TypeScript 中的型別守衛是什麼?


在 TypeScript 中,型別守衛用於確定變數的型別,通常在條件語句或函式塊內部。型別守衛通常接收變數並返回布林值或變數型別。型別守衛允許您告訴 TypeScript 編譯器在特定上下文中推斷變數的給定型別,從而保證引數的型別與您宣告的一致。

與特性檢測類似,型別守衛常用於限制類型,並允許您識別值的正確原型、方法和屬性。因此,處理該值對於使用者來說變得簡單。

使用者可以自定義建立型別守衛,但 TypeScript 也內建了一些運算子,如 'typeof'、'in' 和 'instanceof' 運算子。

在本教程中,我們將討論這些運算子作為型別守衛的用法。

TypeScript 中的 ‘typeof’ 型別守衛

在 TypeScript 中,'typeof' 運算子用於獲取變數的型別。根據變數的型別,它返回以下值:-

  • 數字

  • 字串

  • 布林值

  • 物件

  • 大整數

  • 符號

  • 函式

  • 未定義

語法

使用者可以遵循以下語法來使用 'typeof' 型別守衛運算子。

typeof variable_name

在上述語法中,我們在變數名前使用 typeof 運算子來獲取變數型別。

示例

在以下示例中,我們將使用 TypeScript 中的 'typeof' 型別守衛。我們聲明瞭四個變數,型別分別為 'number'、'string'、'boolean' 和 'object'。之後,我們使用 TypeScript 的 'typeof' 運算子輸出它們的變數型別。

let my_number: number = 123
let my_string: string = 'Tutorialspoint'
let my_boolean: boolean = true
let my_object: { id: number } = { id: 1 }

console.log('type of my_number variable is: ' + typeof my_number)
console.log('type of my_string variable is: ' + typeof my_string)
console.log('type of my_boolean variable is: ' + typeof my_boolean)
console.log('type of my_object variable is: ' + typeof my_object)

編譯後,它將生成以下 JavaScript 程式碼:-

var my_number = 123;
var my_string = 'Tutorialspoint';
var my_boolean = true;
var my_object = { id: 1 };
console.log('type of my_number variable is: ' + typeof my_number);
console.log('type of my_string variable is: ' + typeof my_string);
console.log('type of my_boolean variable is: ' + typeof my_boolean);
console.log('type of my_object variable is: ' + typeof my_object);

輸出

上述程式碼將產生以下輸出:-

type of my_number variable is: number
type of my_string variable is: string
type of my_boolean variable is: boolean
type of my_object variable is: object

在上述輸出中,使用者可以看到 'typeof' 運算子對四個變數('number'、'string'、'boolean' 和 'object')的輸出。

TypeScript 中的 ‘in’ 型別守衛

‘in’ 型別守衛用於確定物件是否包含特定屬性,然後用於區分不同的型別。它通常返回一個布林值,指示該屬性是否存在於物件中。它被用於其縮小特性。

語法

使用者可以遵循以下語法來使用 'in' 型別守衛運算子。

property_name in object_name

在上述語法中,我們使用 'in' 運算子來查詢屬性是否存在於物件中。

示例

在以下示例中,我們將使用 TypeScript 中的 'in' 型別守衛。我們聲明瞭三個包含不同屬性的物件。我們使用 'in' 型別守衛來檢查物件中是否存在所需的屬性。我們甚至可以檢查屬性是否包含另一個屬性或是否未使用它。在 'obj3' 中,我們檢查物件的屬性是否包含另一個屬性。

let obj1: { id: number; name: string } = { id: 1, name: 'Tutorialspoint' }
let obj2: { name: string; roll: number } = { name: 'XYZ', roll: 12 }
let obj3: { id: number; marks: { english: number; math: number } } = {
   id: 101,
   marks: {
      math: 90,
      english: 80,
   },
}

console.log('Is name is in obj1? => ' + ('name' in obj1))
console.log('Is id is in obj2? => ' + ('id' in obj2))
console.log('Is marks is in obj3? => ' + ('marks' in obj3))
console.log('Is math is in obj3.marks? => ' + ('math' in obj3.marks))

編譯後,它將生成以下 JavaScript 程式碼:-

var obj1 = { id: 1, name: 'Tutorialspoint' };
var obj2 = { name: 'XYZ', roll: 12 };
var obj3 = {
   id: 101,
   marks: {
      math: 90,
      english: 80
   }
};
console.log('Is name is in obj1? => ' + ('name' in obj1));
console.log('Is id is in obj2? => ' + ('id' in obj2));
console.log('Is marks is in obj3? => ' + ('marks' in obj3));
console.log('Is math is in obj3.marks? => ' + ('math' in obj3.marks));

輸出

上述程式碼將產生以下輸出:-

Is name is in obj1? => true
Is id is in obj2? => false
Is marks is in obj3? => true
Is math is in obj3.marks? => true

在上述輸出中,使用者可以看到 'in' 運算子在程式碼中不同情況下產生的輸出。

TypeScript 中的 ‘instanceof’ 型別守衛

‘instanceof’ 是一個內建的型別守衛,用於確定一個值是否為特定建構函式或類的例項。我們可以使用此型別守衛透過測試物件或值是否派生自某個類來確定例項型別的型別。

語法

使用者可以遵循以下語法來使用 'instanceof' 型別守衛運算子。

object_name instanceof class_name

在上述語法中,我們使用 'instanceof' 運算子來查詢物件是否為類的例項。

示例

在以下示例中,我們將使用 TypeScript 中的 'instanceof' 型別守衛。我們聲明瞭一個 'Parent' 類和一個子類 'Child'。我們宣告 'Child' 類的物件並使用 'instanceof' 運算子查詢物件屬於哪個類。

class Parent {
   id: number
   constructor(id: number) {
      this.id = id
   }
}

class Child extends Parent {
   id: number
   name: string

   constructor(id: number, name: string) {
      super(id)
      this.name = name
   }
}

let child = new Child(101, 'ABC')

console.log('child instanceof Child => ' + (child instanceof Child))
console.log('child instanceof Parent => ' + (child instanceof Parent))

編譯後,它將生成以下 JavaScript 程式碼:-

var __extends = (this && this.__extends) || (function () {
   var extendStatics = function (d, b) {
      extendStatics = Object.setPrototypeOf ||
         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
      return extendStatics(d, b);
   };
   return function (d, b) {
      extendStatics(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
   };
})();
var Parent = /** @class */ (function () {
   function Parent(id) {
      this.id = id;
   }
   return Parent;
}());
var Child = /** @class */ (function (_super) {
   __extends(Child, _super);
   function Child(id, name) {
      var _this = _super.call(this, id) || this;
      _this.name = name;
      return _this;
   }
   return Child;
}(Parent));
var child = new Child(101, 'ABC');
console.log('child instanceof Child => ' + (child instanceof Child));
console.log('child instanceof Parent => ' + (child instanceof Parent));

輸出

上述程式碼將產生以下輸出:-

child instanceof Child => true
child instanceof Parent => true

在上述輸出中,使用者可以看到在使用不同類及其物件時 'instanceof' 運算子的輸出。

更新於:2022-12-19

3K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.