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

Suggestion: narrower parameters for NumberConstructor #20754

Closed
danvk opened this issue Dec 18, 2017 · 1 comment
Closed

Suggestion: narrower parameters for NumberConstructor #20754

danvk opened this issue Dec 18, 2017 · 1 comment
Labels
Suggestion An idea for TypeScript Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@danvk
Copy link
Contributor

danvk commented Dec 18, 2017

TypeScript Version: 2.6.2

Code

function foo() {
    return 1234;
}

const num = Number(foo);
// intent was probably:
// const num = foo();

Expected behavior: Number(foo) should be an error.

Actual behavior: Type checks. num is NaN at runtime.

I assume this is WAI, but figured I'd ask. This came up when I got a type error in a math expression, something like 2 * box.width. I didn't read the error closely and assumed the issue was that box.width was a string. So I made it 2 * Number(box.width). This made the error go away, but introduced NaNs at runtime.

Number is declared as:

const Number: NumberConstructor(value?: any) => number

could we make this narrower? maybe

const Number: NumberConstructor(value?: string|number|Date|boolean) => number
@DanielRosenwasser DanielRosenwasser added the Suggestion An idea for TypeScript label Dec 18, 2017
@mhegazy mhegazy added the In Discussion Not yet reached consensus label Jan 10, 2018
@RyanCavanaugh RyanCavanaugh added Working as Intended The behavior described is the intended behavior; this is not a bug and removed In Discussion Not yet reached consensus labels Feb 5, 2018
@RyanCavanaugh
Copy link
Member

The "uncalled function" problem is more broad than Number(x); we speculate about a type that means "anything except a callable function" that would be the input type to a lot of coercion operators, though the existence of classes with static properties really muddies the waters. It's arguable that the object type should have excluded function types, even though (function() { }) instanceof Object is true.

Anyway "pass it to Number" is sort of the "big hammer" to coerce anything to a number and we'd rather not break legit (if odd) uses of that function.

In conclusion, JavaScript is a land of contrasts.

@microsoft microsoft locked and limited conversation to collaborators Jul 3, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Suggestion An idea for TypeScript Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

4 participants