5

In TypeScript 2.0, why can I have a function type guard:

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():

'{' or ';' expected.

4

1 回答 1

3

这里有几个问题:

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

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

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

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

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

于 2016-09-24T10:20:13.697 回答