microsoft / microsoft/TypeScript
const/readonly assertion support for `Map` and `Set`
还没有人认领这个 Issue。
- 主要语言
- Go
- 星标
- 111k
- 派生
- 14.3k
- 平均合并
- 2 天 4 小时
- 30 天内合并 PR
- 132
描述
### 🔍 Search Terms
"as const", "as readonly", "const assertion", "keyed collections"
### ✅ Viability Checklist
- [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code
- [x] This wouldn't change the runtime behavior of existing JavaScript code
- [x] This could be implemented without emitting different JS based on the types of the expressions
- [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- [x] This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- [x] This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
### ⭐ Suggestion
Have a way to take an existing `Map` or `Set` and assert it to be its readonly variant without needing to repeat the generic types.
### 📃 Motivating Example
Today we can create maps (and sets) with explicit and inferred generic types but in order to make them readonly the generic types have to be explicitly written, sometimes repeated:
```ts
const exampleMap1: ReadonlyMap = new Map([["a", 1], ["b", 2]]);
const exampleMap2: ReadonlyMap = new Map().set('a', 1).set('b', 2);
```
With something like const assertion support for `Map` (and `Set`) we'd be able to get readonly maps and sets without repeating the generic types:
```ts
const exampleMap1 = new Map([["a", 1], ["b", 2]]) as const;
const exampleMap2 = new Map().set("a", 1).set("b", 2) as const;
```
### 💻 Use Cases
1. What do you want to use this for? I want to use this for creating keyed collections that will be used elsewhere and I want to avoid modifications. (Note: this won't prevent runtime modifications but the same is true for const assertions on arrays and objects today.)
2. What shortcomings exist with current approaches? Repetative generic types and verbose code to make a keyed collection readonly.
3. What workarounds are you using in the meantime? Repeating the generic types and explicitly defining things as readonly keyed collections.
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先检查 TypeScript 对数组和对象的 const 断言行为,以及现有的 Map 和 Set 类型检查规则。确定如何在不重复泛型类型的情况下表示 readonly 键控集合,然后添加覆盖测试,展示所提出的断言能够推断出 readonly Map 和 Set 类型,同时保留当前的 JavaScript 输出。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- typescript
- 领域
- compilers
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 25/100