microsoft / microsoft/TypeScript

`as const` breaks intra expression inference

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

还没有人认领这个 Issue。

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

描述

### 🔎 Search Terms

const context expression assertion inference type parameter

### 🕗 Version & Regression Information

- This is the behavior in every version I tried

### ⏯ Playground Link

https://www.typescriptlang.org/play/?ts=6.0.0-dev.20250806#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXwxAGcMAeAFQBp4ARAPgApYBzALngG8AoeeLVAA7IM7GgG4e8ATBzBkYEOyYw2tAJTwAvHXjkJvMHiLIAtovjLV5DdvipTAIxAwJAXzWiJXQ6hLwHMgDWIPiaBMQYDNy8-EIi8ACMAAxJlJLSsvLmljY6LAB0GDgAyhgw-MwMamkGRqbZLLnwBRAhzBgAFmmuzUTwPiRqXgMY8ADuODCBFVrhJFGSscLsyanpMnIKSo1aeSqFJWUVVTX9dWbbKk0tbZ3dQ1xAA

### 💻 Code

```ts
declare function test(arg: {
input: D;
produce: (arg: D) => T;
consume: (arg: T) => number;
}): D;

const broken = test({
input: 100,
produce: (arg) => arg.toString(), // 'arg' is of type 'unknown'.(18046)
consume: (arg) => arg.length,
} as const);

const working = test({
input: 100,
produce: (arg) => arg.toString(), // `arg` inferred as `number`
consume: (arg) => arg.length,
});
```

### 🙁 Actual behavior

`as const` is the only difference between those two and its presence breaks assigned parameter type in `produce`

### 🙂 Expected behavior

I think `as const` should not impact inference this way and both should be inferred just OK. It's just that the `broken` case should infer `100` instead of `number` for the `D` type parameter

### Additional information about the issue

_No response_

贡献指南

打开贡献指南

从这里开始

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

调研方向

从链接的 TypeScript Playground 开始,比较 `broken` 和 `working` 示例,然后跟踪 `as const` 断言如何影响 `produce` 的上下文类型和推断。完成的标准是:在使用断言的情况下,回调参数能够在没有 `unknown` 的情况下完成推断,并保留对 `D` 预期的字面量 `100` 推断。

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

评估

技术栈
typescript
领域
compilers
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
42/100

把新 issue 发到你的邮箱

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