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

Narrowing from "any" using instanceOf will overwrite another narrowing expression in "||" #10398

Closed
yuit opened this issue Aug 17, 2016 · 5 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@yuit
Copy link
Contributor

yuit commented Aug 17, 2016

TypeScript Version: build from master 8/17

function foo(x: any) {
    if (typeof (x) === 'number' || x instanceof Number) {
        isNaN(x)  // error x has type Number
    }
}

Note: this doesn't happen if parameter x has type number | Number

@yuit yuit added the Bug A bug in TypeScript label Aug 17, 2016
@RyanCavanaugh
Copy link
Member

But this is still an error if we correctly narrow to number | Number -- isNaN(new Number(3)) is not permitted (though maybe it should? Hard to say)

@yuit
Copy link
Contributor Author

yuit commented Aug 17, 2016

@RyanCavanaugh true; Though the error message is confusing then since you will be like why the type is only number

@weswigham
Copy link
Member

isNaN coerces to a number with valueOf before checking (isNaN({}) === true), so it's conceivable that it should just have a wider argument type, rather than strictly number.

@DanielRosenwasser
Copy link
Member

@weswigham see #4002 and #3947.

@ahejlsberg
Copy link
Member

Since number is a subtype of Number, there's really no difference between number | Number and Number. In control flow analysis we perform subtype reduction at junction points only when the control flow type includes "foreign" types, i.e. types that don't occur in the declared type. The type guards in the if statement in combination produce the type number | Number, which then gets subtype reduced to Number if the body of the if statement. But this subtype reduction doesn't happen when the declared type itself is number | Number because the types aren't considered foreign.

@ahejlsberg ahejlsberg added Working as Intended The behavior described is the intended behavior; this is not a bug and removed Bug A bug in TypeScript labels Aug 18, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

5 participants