Skip to content

strictNullChecks safeguards against null and undefined, but not NaN #21279

Closed
@MarvinHannott

Description

@MarvinHannott

Code

// simple convertion
let n: number = Number("not-a-number") // could be NaN

// function that returns NaN
function couldBeNaN(x: any): number {
     if(typeof x === "number"){
            return x;
     }
     return NaN
}

n = couldBeNaN("not-a-number") // will return NaN 

Expected behavior:
A safeguard against NaN as there is for null and undefined.

// simple convertion
let n: number | NaN = Number("not-a-number") // enforced check

// function that returns NaN
function couldBeNaN(x: any): number | NaN {
     if(typeof x === "number"){
            return x;
     }
     return NaN
}

n = couldBeNaN("not-a-number") // will return NaN, but it's okay 

Hence NaN isn't a type in TypeScript, this isn't possible.

Actual behavior:
NaN passes as a regular number although it is the direct opposite (yes, I know it is defined as such in the ECMAScript-standard, but nonetheless, it almost always hits you unexpected).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions