microsoft / microsoft/TypeScript

Support type inference for Symbol keys on function

未关闭
#61,214 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Domain: check: Type Inference Help Wanted Possible Improvement
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
132

描述

🔍 Search Terms

symbol index closure function ts7022

✅ Viability Checklist
⭐ Suggestion

Typescript doesn't correctly infer the type when using a symbol as the key when adding a property to a function type.

Here is an example:

const TestSymbol: unique symbol = Symbol();

const c = () => {
  return 'Hello, world!';
};
c['testProp'] = ['Hello']; // String property is correctly inferred to be of the type string[]
c[TestSymbol] = ['Hello']; // Typescript complains about the type being implicitly any.

c[TestSymbol] = ['Hello'] as string[] // This works as a workaround for this limitation in typescript.

The full error from the language server:

c[TestSymbol] implicitly has type 'any' because it does not have a type annotation
and is referenced directly or indirectly in its own initializer. (tsserver 7022)

Using a symbol this way works without any issues in plain javascript. I've tested Firefox, Chromium, Node and Bun and all these runtimes handle using symbols as property keys on a function without any issue.

It is very limiting not being able to use symbols naturally in typescript the same way they work in javascript. It would be great if typescript could infer the type of the property when using a symbol as the key the same way it does when using a string for the key.

📃 Motivating Example

I've not written any blog posts about this.

💻 Use Cases
  1. What do you want to use this for? I'm building some infrastructure code where I want to append some information to various objects. Using symbols removes the risk of key collisions that can occur when using strings.
  2. What shortcomings exist with current approaches? Using strings instead of symbols or manually casting to the expected type can lead to unexpected collisions and type errors.
  3. What workarounds are you using in the meantime? Strings and manually casting to the expected type.

贡献指南

打开贡献指南

从这里开始

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

调研方向

首先复现函数属性示例及其 tsserver 7022 诊断。未指定源文件或测试,因此请跟踪编译器对计算属性符号和相关推断案例的处理。完成的标准是:符号键赋值能够在没有显式注解的情况下推断出其属性类型,同时现有的字符串键行为保持不变。

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

评估

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

把新 issue 发到你的邮箱

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