TypeScript: Comparing == null does not work as type guard when explicitNullChecks is disabled

TypeScript Version: 2.6.1

Code

(with “strictNullChecks” disabled)

function foo(value: number | null | undefined): string | null | undefined {
    if (value == null) {
        return value;
    }

    return value.toString();
}

Expected behavior: Compile without errors.

Actual behavior: “Type ‘number’ is not assignable to ‘string’” at the “return value” line

screen shot 2017-11-09 at 1 35 34 pm

Enabling “strictNullChecks” causes the code to compile without error, but I unfortunately cannot enable strictNullChecks in my project due to a 3rd party typescript library that was not designed with structNullChecks.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 16 (7 by maintainers)

Most upvoted comments

@UselessPickles based on your description, what you’re missing is how pre-strictNullChecks checking works.

With SNC off, there is no distinction about whether a value is null or not. There’s no distinctions, anywhere, about what null means, whether something has been determined to be null or not, or when something may or may not be null. It’s just completely untracked; type guards checking for null do nothing.

When --strictNullChecks is not enabled, every type implicitly includes null and undefined. Therefore, from a type level perspective, the function

declare function foo(value: number | null | undefined): string | null | undefined;

is equivalent to

declare function foo(value: number): string;

The only difference is that the former is more self-documenting.