Search code examples
typescriptstrict

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'.

In strict mode, typescript warns about uses of possibly undefined properties. And amazingly it is able to detect logic preventing that (as it does in the line commented "standard check".

But if the logic is more hidden as in the "custom check" it doesn't. I don't expect it to be that extrasuper smart but what would be a way to state that the property is validated? (the example is trivial but in more complex cases it may be necessary)


Solution

  • In such cases, where the TypeScript compiler cannot figure out that the property is not null or undefined, you can use the ! (Non-null assertion operator).

    In your case, it would mean:

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

    This effectively tells the compiler that you know the property is defined at this point, even though the compiler cannot figure it out.

    More information here: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html