TypeScript 2.0 方法类型保护?

jrb*_*ard 5 typescript typescript2.0

在 TypeScript 2.0 中,为什么我可以有一个函数类型保护:

function hasValue<T>(value: T | undefined): value is T { return value !== undefined; }
Run Code Online (Sandbox Code Playgroud)

但不是方法类型保护?:

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

    hasValue(): this.value is T { return this.value !== undefined; }
}
Run Code Online (Sandbox Code Playgroud)

错误hasValue()

'{' 或者 ';' 预期的。

Nit*_*mer 3

这里有几个问题:

1)当使用this声明返回类型时,它被用作多态 this 类型,而不是作为对该类实例的引用。

2)关于此事的文档明确指出:

谓词采用parameterName is Type 的形式,其中parameterName 必须是当前函数签名中的参数名称。

如果您使用this.parameterName,那么它不是“当前函数签名的参数”。
你可能会争辩说他们可以添加它,但随后:

3) 类型保护是检查类型而不是变量的函数。
由于类型本身不是类的一部分,因此类型保护函数也不会成为类的一部分是有道理的。