TypeScript 中的类型保护是什么?

typescriptserver side programmingprogramming更新于 2025/10/10 15:07:17

在 TypeScript 中,类型保护用于确定变量的类型,通常用于条件块或函数块中。类型保护通常接收变量并返回布尔值或变量类型。类型保护允许您指示 TypeScript 编译器在特定上下文中推断变量的给定类型,从而保证参数的类型与您指定的一致。

与特性检测类似,类型保护通常用于限制类型,并帮助您识别值的正确原型、方法和属性。因此,用户处理该值变得非常简单。

TypeScript 中可以创建用户定义的类型保护,但它也具有内置运算符,例如"typeof"、"in"和"instanceof"运算符。

在本教程中,我们将讨论这些运算符作为类型保护的用法。

TypeScript 中的"typeof"类型保护

在 TypeScript 中,"typeof"运算符用于获取变量的类型。根据变量的类型,它返回如下值:-

  • Number

  • String

  • Boolean

  • Object

  • Bigint

  • Symbol

  • Function

  • Undefined

语法

用户可以按照以下语法使用"typeof"类型保护运算符。

typeof 变量名

在上述语法中,我们在变量名前使用 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('my_number 变量的类型为:' + typeof my_number);
console.log('my_string 变量的类型为:' + typeof my_string);
console.log('my_boolean 变量的类型为:' + typeof my_boolean);
console.log('my_object 变量的类型为:' + typeof my_object);

输出

上述代码将产生以下输出 -

my_number 变量的类型为:number
my_string 变量的类型为:string
my_boolean 变量的类型为:boolean
my_object 变量的类型为: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 实例化 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"运算符在不同的类及其对象中使用时的输出。


相关文章