You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript为何无法对数组末尾可选元素进行条件推断?

为什么这个TypeScript条件类型返回'BAD'?

为什么以下条件类型会返回'BAD'?

type X = [string[], string[], {
  a?: boolean;
  b?: boolean;
}?] extends [...infer A, infer B] ? B : 'BAD';

// A == 'BAD'
// B == 'BAD'

但如果将末尾元素设为非可选,或是把可选元素移至数组中间或开头(这会触发TS1257不健全提示,但仍能满足示例的条件),则能按预期完成扩展与推断:

type Y = [string[], string[], {
  a?: boolean;
  b?: boolean;
}] extends [...infer A, infer B] ? B : 'BAD';

// A == [string[], string[]]
// B == { a?: boolean; b?: boolean; }
// 此代码触发TS1257(如上文所述),但仍能得到正确推断:
type Z = [string[], {
  a?: boolean;
  b?: boolean;
}?, string[]] extends [...infer A, infer B] ? B : 'BAD';

// A == [string[], { a?: boolean; b?: boolean; } | undefined]
// B == string[]

内容的提问来源于stack exchange,提问作者Xunnamius

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 14:16:00