microsoft / microsoft/TypeScript

Improved `NumberConstructor` for literal types

Open
#62,308 5 comments 1 reaction 0 assignees View on GitHub
Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
PR merge metrics
PR metrics pending

Description

### ⚙ Compilation target

esnext

### ⚙ Library

esnext

### Missing / Incorrect Definition

`NumberConstructor(value?: any): number`:
https://github.com/microsoft/TypeScript/blob/261630d650c0c961860187bebc86e25c3707c05d/src/lib/es5.d.ts#L570-L572

This is correct but I think could be improved to work better when converting string literals to numbers by returning number literals. This could be achieved by doing something like
```typescript
(value?: T): T extends `${infer N extends number}` ? N : number;
```

See [this playground link](https://www.typescriptlang.org/play/?ts=6.0.0-dev.20250820#code/MYewdgzgLgBAgjAvDARARgEwoNwChSSwBCAXDJkjAHICuAtgEYCmATgBRwCU2MMA9HxgAVAJ4AHJjADkYesxZSYASwgwwIWAEMIEJQHMwmhgBtJUEDCjjJUzFIB0ufOGjwMZdFhgAfVGgDMKD5+ACxByJ44zoQwRO7kGMEBSSGUtIysHBjcvALC1tKyGQrKqupaOvqGJmYWVhLSFL7JzSEOTk4AZjRgwFBK4DAEAG4APEIAfGzDmsYA-GRCnIswTAAeUExgACaqAAYAJADeSmCdrNSrG1u7anKsAL57MHOXZEXyMEe4vLmCAAJQCAAWnWEj6oJYLBALB+vxYTCgNBYYGo93YM2M3FwDycBFccDgHkw4T8WB4-EEQgAFioYJowOVNP1BnSEQBHGhKBHbGCdGEwCAgOiSBHaQbmGB0TQAazM1LM1lUAHcYTLoq4iKQEpQRhwuHgNbBCfFIsF0IFzWgwpRInh8cQ4mQmuR-CldeBhvrsnggA)

### Sample Code

```TypeScript
const A = "12";
const B: 12 = Number(A); // Type 'number' is not assignable to type '12'.

const A2: "12" | "13" | "14" = "12";
const B2: 12 | 13 | 14 = Number(A2); // Type 'number' is not assignable to type '12 | 13 | 14'.
```

### Documentation Link

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number

Contributor guide

Open the contributing guide

Research direction

Start with the NumberConstructor declaration in src/lib/es5.d.ts at the linked lines, then reproduce the supplied samples and playground behavior. Review the MDN Number documentation to compare runtime conversion with the proposed literal-type result. Done means the declaration handles the shown literal and union examples without incorrectly narrowing general values.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.