Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invalid type coercion with == operator and strings #24991

Closed
Wintermoose opened this issue Jun 15, 2018 · 1 comment · Fixed by #29840
Closed

Invalid type coercion with == operator and strings #24991

Wintermoose opened this issue Jun 15, 2018 · 1 comment · Fixed by #29840
Labels
Bug A bug in TypeScript Help Wanted You can do this
Milestone

Comments

@Wintermoose
Copy link

TypeScript Version: typescript@3.0.0-dev.20180609, 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)

@ghost ghost added the Bug A bug in TypeScript label Jun 15, 2018
@mhegazy mhegazy added the Help Wanted You can do this label Jun 19, 2018
@mhegazy mhegazy added this to the Community milestone Jun 19, 2018
@Kingwl
Copy link
Contributor

Kingwl commented Jun 22, 2018

seems narrow type in narrowTypeByEquality not handle the Relax Equal Operator
i would like to add a new type comparable similar areTypesComparable,
that handle the Relax Equal Operator and narrow type
follow the rule: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Help Wanted You can do this
Projects
None yet
4 participants