Skip to content

Comparison operator is prohibited for nulls, but is allowed for union types containing the null type (with strictNullChecks turned on). #13863

Closed
@Nipheris

Description

@Nipheris

TypeScript Version: 2.1.5

Code

--strictNullChecks should be enabled.

const nil = null;

// Compile error:
// "Operator '<' cannot be applied to types 'null' and 'number'"
if (nil < 10) { }

// Use function to trick the type narrowing
function test(): number | null {
    return null;
}

const n = test();
// OK
if (n < 1) { }

Expected behavior:
Both comparisons should generate a compilation error.

Actual behavior:
The first comparison (nil < 10) fails to compile (as expected), but the second one (n < 1) compiles successfully.

It seems odd that the same operation (less-than number) is not allowed for null (what is completely fine), but allowed for union type that includes null. If there are some solid reasons to behave this way, I think they should be mentioned in the language guide (can't find something about it).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs InvestigationThis issue needs a team member to investigate its status.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions