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

TypeScript疑问:可选变量为何不触发Spread types错误?为何undefined扩展报错?

TypeScript 扩展运算符类型问题解答
let thing: string | undefined;

const obj = {
  a: 1,
  ...(thing && { b: 2 }),
};

const obj2 = {
  a: 1,
  ...(undefined && { b: 2 }),
};

obj2会触发TypeScript错误:"Spread types may only be created from object types."

问题1:既然thing的类型为string | undefined(可能为undefined),为什么obj不会触发同样的错误?

thing && { b: 2 }的类型是{ b: number } | undefined:当thing为字符串(真值)时,表达式返回{b:2}这个对象;当thing为undefined时,返回undefined。TypeScript对这种包含对象类型的联合类型做了特殊处理——它知道运行时扩展undefined会被忽略,且联合类型中存在合法的对象分支,因此允许这种写法,不会报错。

问题2:既然{...(undefined)}在JavaScript中是合法语法,为什么TypeScript会触发该错误?

JavaScript里{...undefined}确实合法,运行时会直接忽略undefined,但TypeScript的设计目标之一是提前捕获无意义或大概率为笔误的代码。直接写...undefined几乎没有合理的业务场景,大概率是开发者的失误(比如本应写某个变量却误写了undefined),因此TypeScript通过报错提醒开发者修正这种无意义的写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 17:13:24