Why does TypeScript allow null assignment within ternary under strictNullChecks?

170 Views Asked by At

I'm new to TypeScript, but I see seemingly inconsistent behavior: I can assign null to an interface as part of a ternary assignment, but I get an error when doing so via if/else flow (please see below).

The project is set to enforce strictNullChecks, so I expect error 2322 from both approaches.

What am I missing?

'use strict';

//NOTE: The following is set in tsconfig.json:
//      "strictNullChecks": true

const CONDITIONALLY_ASSIGNED:any = 0;

interface IFoo {
    unused: string;
}

export class Bar {
    _testFlow:IFoo;
    _testTernary:IFoo;

    constructor() {
        const FORK:boolean = Math.random() < 0.5;

        this._testTernary = FORK ? CONDITIONALLY_ASSIGNED : null; // no error; why not?

        if (FORK) {
            this._testFlow = CONDITIONALLY_ASSIGNED;
            return;
        }

        this._testFlow = null; // ERROR: "Type 'null' is not assignable to type 'IFoo'.ts(2322)"
    }
}
0

There are 0 best solutions below