Skip to content

Invalid type coercion with == operator and strings #24991

Closed
@Wintermoose

Description

@Wintermoose

TypeScript Version: [email protected], 2.9.2, playround

Search Terms:
== as typeguard
number typeguard
number type coercion

Code

function test(level: number | string):number {
    if (level == +level) {
        const q2 = level; //number
        return level;
    }
    return 0;
}
alert(test(5) + 1);
alert(test("5") + 1) 

Expected behavior:
Compiler error

Actual behavior:
The code compiles. As mentioned in the comment, typescript assumes that level inside the if block is a number; however in reality that condition passes also for number-like string ("5")

Playground Link:
http://www.typescriptlang.org/play/index.html#src=function%20test(level%3A%20number%20%7C%20string)%3A%20number%20%7B%0D%0A%20%20%20%20if%20(level%20%3D%3D%20%2Blevel)%20%7B%0D%0A%20%20%20%20%20%20%20%20const%20q2%20%3D%20level%3B%20%2F%2Fnumber%0D%0A%20%20%20%20%20%20%20%20return%20level%3B%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20return%200%3B%0D%0A%7D%0D%0A%0D%0Aalert(test(5)%20%2B%201)%3B%0D%0Aalert(test(%225%22)%20%2B%201)

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptHelp WantedYou can do this

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions