假设下面的验证器类
class Validator<T> {
private readonly data: T;
public constructor(data: T) {
this.data = data;
}
public isDefined(): this.data is NonNullable<T> { // This is invalid
return typeof this.data !== 'undefined';
}
}我正在尝试弄清楚如何在this.data的isDefined函数中添加不可为空的typeguard。上面的示例是无效的,并且在this.data中出现以下错误
(property) Validator<T>.data: T
Duplicate identifier 'data'.ts(2300)
All declarations of 'data' must have identical modifiers.ts(2687)
Subsequent property declarations must have the same type. Property 'data' must be of type 'T', but here has type 'any'.ts(2717)
validation.ts(11, 20): 'data' was also declared here.我计划在下面这样的场景中使用它:
const myNumber: number | undefined = 1234;
if (new Validator(myNumber).isDefined()) {
console.log(myNumber) // Typescript should only see this as number
}发布于 2020-07-21 18:17:38
只有在引用validator.data而不是引用外部作用域中的自由变量时,它才会起作用。
class Validator<T> {
constructor(readonly data: T) {}
isDefined(): this is Validator<NonNullable<T>> {
return (
this.data !== null && this.data !== undefined
);
}
}
declare const myNumber: number | undefined;
const validator = new Validator(myNumber);
if (validator.isDefined()) {
validator.data;
}https://stackoverflow.com/questions/63011751
复制相似问题