microsoft / microsoft/TypeScript
Improved `NumberConstructor` for literal types
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.3k
- Merge medio
- 2g 4h
- PR unite (30g)
- 132
Descrizione
### ⚙ 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
Guida per i contributori
Apri la guida per i contributori
Direzione di ricerca
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.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- javascript, typescript
- Ambito
- compilers
- Tipo di issue
- Funzionalità
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Specificata chiaramente
- Idoneità per principianti
- 35/100