【问题标题】:TypeScript 2.0 method type guards?TypeScript 2.0 方法类型保护?
【发布时间】:2016-09-24 18:20:13
【问题描述】:

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

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

但不是方法类型的守卫?:

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

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

hasValue() 出错:

'{' 或 ';'预计。

【问题讨论】:

  • 这与 TypeScript 2.0 有关吗?无论如何,value in T 中的标识符必须是范围内的某个标识符,例如参数。无论守卫是在函数还是方法上,这都是正确的。您可以将您的守卫写为hasValue&lt;T&gt;(value) value is T { return value !== undefined; },并将其称为if (this.hasValue(this.value)) ...

标签: typescript typescript2.0


【解决方案1】:

这里有几个问题:

1) 在声明返回类型时使用this 时,它被用作polymorphic this type 而不是对类实例的引用。

2) The docs on this matter 明确声明:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 2021-01-22
    • 2019-01-04
    • 2020-11-11
    • 2021-12-10
    • 2018-12-03
    • 1970-01-01
    相关资源
    最近更新 更多