【发布时间】: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<T>(value) value is T { return value !== undefined; },并将其称为if (this.hasValue(this.value)) ...。