简体   繁体   English

TypeScript 2.0方法类型保护?

[英]TypeScript 2.0 method type guards?

In TypeScript 2.0, why can I have a function type guard: 在TypeScript 2.0中,为什么我有一个函数类型保护:

function hasValue<T>(value: T | undefined): value is T { return value !== undefined; }

But not a method type guard?: 但不是方法型护卫?:

export class Maybe<T> {
    constructor(public value: T | undefined) {}

    hasValue(): this.value is T { return this.value !== undefined; }
}

error on hasValue() : hasValue()出错:

'{' or ';' '{' 要么 ';' expected. 预期。

There are a few issues here: 这里有一些问题:

1) When using this when declaring the return type then it's used as polymorphic this type and not as a reference to the instance of the class. 1)在声明返回类型时使用this时,它被用作这种类型的多态,而不是对类实例的引用。

2) The docs on this matter clearly state that: 2) 关于此事的文件明确指出:

A predicate takes the form parameterName is Type, where parameterName must be the name of a parameter from the current function signature. 谓词采用参数形式parameterName是Type,其中parameterName必须是当前函数签名中参数的名称。

If you use this.parameterName then it isn't "a parameter from the current function signature". 如果使用this.parameterName则它不是“当前函数签名中的参数”。
You could argue that they could add it but then: 您可以争辩说他们可以添加它但是然后:

3) Type guards are functions which check a type and not a variable. 3)类型保护是检查类型而不是变量的函数。
As the type itself isn't a part of the class then it makes sense that the type guard function won't be a part of the class as well. 由于类型本身不是类的一部分,因此类型保护函数也不会成为类的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM