typescriptstrictnullchecks

Typescript with --strictNullCheck - check not null in separate method


I am having fun with the compiler --strictNullCheck option

I have this method:

enter image description here

enter image description here

I need to check if the headers are not null before i can use them. That's great

Now I would like to move the checking operation to the separate method like this:

enter image description here

But not I'm getting this error:

enter image description here

So there is no way to check if some object or the some of its property is not null in the separate method?


Solution

  • Use a type guard. A type guard is some expression that performs a runtime check that guarantees the type in some scope.

    In your case something like this may work (its hard to tell since you pasted images instead of code):

    function hasHeaders(error: Response): error is Response & { headers: Headers} {
        return error.headers != null
    }
    

    You can learn more about type guards in typescript handbook at https://www.typescriptlang.org/docs/handbook/advanced-types.html