打字稿严格。状态 属性 不是未定义的

typescript strict. state property is not undefined

class AClass{
    aProp?:number=undefined;
    HasAProp():boolean{return this.aProp!==undefined;}
}
let anInst=new AClass;
if (anInst.aProp)     // standard check
    Math.sqrt(anInst.aProp);

if (anInst.HasAProp())    // custom check
    Math.sin(anInst.aProp);     // ts error:  Argument of type 'number | undefined' is not assignable to parameter of type 'number'.

在严格模式下,typescript 会警告使用可能未定义的属性。令人惊讶的是,它能够检测到阻止这种情况的逻辑(正如它在注释行 "standard check".

中所做的那样)

但是如果逻辑像 "custom check" 那样更隐蔽,它就不会。我不希望它那么聪明,但有什么方法可以表明 属性 已通过验证? (这个例子很简单,但在更复杂的情况下可能是必要的)

您可以使用 is

class AClass {
    aProp?: number = undefined;
    HasAProp(aProp: this['aProp']): aProp is number {
        return aProp !== undefined;
    }
}

let anInst = new AClass;
if (anInst.aProp)
    Math.sqrt(anInst.aProp);

if (anInst.HasAProp(anInst.aProp))
    Math.sin(anInst.aProp);

我不确定是否可以不将 aProp 作为参数传递给 HasAProp()

在这种情况下,TypeScript 编译器无法确定 属性 不是 nullundefined,您可以使用 !(非空断言运算符)。

在你的情况下,这意味着:

if (anInst.HasAProp(anInst.aProp))
    Math.sin(anInst.aProp!);

这有效地告诉编译器您知道 属性 已在此时定义,即使编译器无法识别。

这里有更多信息:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html