我正在阅读用 Typescript 编写的代码。不知道我理解是否正确:
export class MyClass<B> {
value: B;
constructor(value: B) {
this.value = value;
}
isMyClass(): this is MyClass<B> {
return true;
}
}
<B>
是什么意思?代表?它代表什么,类型?如果是,它是什么类型?什么是
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)
哪里value
是 3
,告诉 TypeScript 结果实例是 MyClass<number>
- 换句话说,它是value
属性(property)拥有 number
,一个B
.
What is
this is MyClass<B>
inisMyClass(): 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/