microsoft / microsoft/TypeScript

Type inference with conditional for array fails for literal

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

还没有人认领这个 Issue。

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

描述

TypeScript Version: 3.9.2

Search Terms: typescript infer array type conditional literal

Code

function func<T>(opt: {
  value: T;
  arrayValue: T extends any[] ? T : T[];
}) {}

func({
  value: [1, 2, 3],
  arrayValue: [1, 2, 3],
}); // throws error 

const obj = {
  value: [1, 2, 3],
  arrayValue: [1, 2, 3],
};

func(obj);

Expected behavior:
No error is thrown.

Actual behavior:
The commented function call throws the following error:

Type 'number[]' is not assignable to type 'number'.(2322)
input.ts(2, 3): The expected type comes from property 'value' which is declared here on type '{ value: number; arrayValue: number[]; }'

Playground Link: https://www.typescriptlang.org/play/#code/GYVwdgxgLglg9mABKSAeAKgPgBRwA5QBciA3gFCKIBuAhgDYgCmx6A3BYjQE5c0CeANXpMWiRgA8ojMABMAzpzB8A2gF1EAfkTpELNewC+ASlIGyZFBGzlKtBs0TKAjABpEAJjcBmVS47deQWEHZzdPRB8-Y3MIBDkoRDgAIwArRABeUg47EUdXD29ffx5+IXtiUIKIooN2C3ArZJSjdiA

Related Issues:

贡献指南

打开贡献指南

从这里开始

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

调研方向

首先在链接的 TypeScript Playground 中复现泛型条件类型示例,并比较直接调用与使用 obj 的调用。跟踪其中涉及的类型推断和条件类型处理;当直接调用不产生错误且保留预期的推断数组类型,并为该示例添加回归测试时,即视为完成。

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

评估

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

把新 issue 发到你的邮箱

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