microsoft / microsoft/TypeScript

Improved `NumberConstructor` for literal types

Offen
#62,308 5 Kommentare 1 Reaktion 0 zugewiesene Personen Auf GitHub ansehen
Awaiting More Feedback Suggestion
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.3k
Ø Merge
2 T. 4 Std.
Gemergte PRs (30 T.)
132

Beschreibung

### ⚙ 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

Beitragsleitfaden

Beitragsleitfaden öffnen

Rechercherichtung

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.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
javascript, typescript
Bereich
compilers
Issue-Typ
Feature
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Aktivitätsstatus
Veraltet
Klarheit
Klar beschrieben
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.