microsoft / microsoft/TypeScript

Improved `NumberConstructor` for literal types

未关闭
#62,308 5 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Awaiting More Feedback Suggestion
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
132

描述

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

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

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.

由索引模型根据 Issue 内容生成。

评估

技术栈
javascript, typescript
领域
compilers
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
描述清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。