Skip to content

Invalid type coercion with == operator and strings #24991

Closed

Description

@Wintermoose

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)

Activity

  1. ghost added
    BugA bug in TypeScript
    on Jun 15, 2018
  2. Kingwl commented on Jun 22, 2018

    @Kingwl
    Contributor

    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

  3. added a commit that references this issue on Apr 26, 2019
    0949ad1
  4. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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