javascript - Typescript 语法澄清

标签 javascript node.js typescript

我正在阅读用 Typescript 编写的代码。不知道我理解是否正确:

export class MyClass<B> {
  value: B;

  constructor(value: B) {
    this.value = value;
  }

  isMyClass(): this is MyClass<B> {
    return true;
  }
}

  1. <B> 是什么意思?代表?它代表什么,类型?如果是,它是什么类型?

  2. 什么是this is MyClass<B>isMyClass(): this is MyClass<B> ?它被评估为真还是假?为什么不将其放在函数本身内部,如下所示:

  isMyClass() {
    if (this is MyClass) {
      return true;
    }
    else {
      return false;
    }    
  }

我无法找到这些问题的答案。

最佳答案

What does the <B> stand for? What does it represent, a Type? If so, what Type is it?

这是一个类型参数,也称为泛型。请参阅TS handbook .

In languages like C# and Java, one of the main tools in the toolbox for creating reusable components is generics, that is, being able to create a component that can work over a variety of types rather than a single one. This allows users to consume these components and use their own types.

每当调用函数或创建实例时,如果该函数或类是通用的,您可以向其“传递”类型参数,类似于将参数传递给函数或类的方式构造函数。 (不同之处在于,类型参数作为类型,并不存在于发出的 JS 中 - 它只是用来帮助 TS 类型检查)。

If so, what Type is it?

它是调用构造函数参数的任何类型。

const m = new MyClass(3);

将导致

constructor(value: B)

哪里value3 ,告诉 TypeScript 结果实例是 MyClass<number> - 换句话说,它是value属性(property)拥有 number ,一个B .

What is this is MyClass<B> in isMyClass(): this is MyClass<B>? Is it being evaluated for true or false? Why not to put this inside of the function itself then, something like this:

isMyClass(): this is MyClass<B> {

type guard 。如果该方法返回 true ,它告诉 TypeScript 该实例的类型为 MyClass<B> .

虽然你可以这样做:

  isMyClass() {
    if (this instanceof MyClass) {
      return true;
    }
    else {
      return false;
    }    
  }

isMyClass 时,TypeScript 无法理解类型已缩小。叫做;它只会返回一个 bool 值。相反,使用 is都会返回一个 bool 值并给出有关调用内容的 TypeScript 类型信息。

关于javascript - Typescript 语法澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64492362/

相关文章:

javascript - 使用 Javascript 配置 Parsley,而不是 html 数据属性

javascript - 使用 html5 canvas 的 JavaScript 中的鼠标单击事件

javascript - Html DOM 到数组缓冲区来为 pdf 制作 BLOB?

node.js - 如何使用 .d.ts 文件

node.js - MongoDB 全文搜索 : Overflow sort stage buffered data usage

javascript - 在 Typescript 中通过 For 循环在 Canvas 上绘制线条不会呈现

javascript - AngularJS:具有不同属性的数组数组中的 ngIf

javascript - CSS 或 HTML 帮助设置图像的最大宽度和高度

javascript - Mongoose populate() 返回对象数组而不是单个对象

javascript - 如何在多个操作之间共享对象的单个实例?