microsoft / microsoft/TypeScript

type parameter variance in generic call signature is incorrectly bivariant

未关闭
#63,677 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Bug Domain: check: Variance Relationships
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
132

描述

🔎 Search Terms

unsound generic function assignability type parameter variance generic call signature bivariant

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about generics and variance.
⏯ Playground Link

https://www.typescriptlang.org/play/?ts=6.0.3#code/C4TwDgpgBAygFgewK4BsAmAhCBJAdgNwEMAnAS0N2AB4ARAPigF4oqAVOgCgA8AuKVgGQ0ANFBB9WASkZ1BNAFDyAxglwBnYFDUQVuNH3jJ0WPETIVqSXAGtcCAO64GzKN1EhJTBiGWqNUZGAAOSQAWwAjCGIDRFRMHAISckoqXDDI4mctHVU0eUCQiKiqK1sHJw4AFlEAcg1iGskAOmAEAFEuMFUISnIUDklFXX9SXEKMmKN40ySLVPSorO5PGVcuFvbO7t7CfslRLkHhzVGAVRs7R0m4k0TzFNLLpyYoUfGo+TOL8o464AbavVGoogA

💻 Code
type ShouldBeInvariant<D> = <T>(x: T&D, y: T)=>T&D

const second: ShouldBeInvariant<unknown> =  (x, y) => y
const outNumber: ShouldBeInvariant<number> = second
outNumber<unknown>(4, 'str').toExponential()

const inNumber: ShouldBeInvariant<number> = (x) => (x.toExponential(), x)
const inUnknown: ShouldBeInvariant<unknown> = inNumber
inUnknown('str', 'str')

🙁 Actual behavior

The code type checks, while it shouldn't because that is unsound, using ShouldBeInvariant covariantly or contravariantly both causes runtime errors.

🙂 Expected behavior

ShouldBeInvariant should be invariant against its parameter. Both assigns:

const outNumber: ShouldBeInvariant<number> = second

and

const inUnknown: ShouldBeInvariant<unknown> = inNumber

should report errors

Additional information about the issue

No response

贡献指南

打开贡献指南

从这里开始

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

调研方向

从链接的 TypeScript Playground 示例开始,重现涉及 ShouldBeInvariant 的不健全赋值。跟踪泛型调用签名的可赋值性和方差检查,然后添加一个回归测试,表明两个赋值都会报告错误,并且无效调用不再通过类型检查。

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

评估

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

把新 issue 发到你的邮箱

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