如何在TypeScript类型化值数组中条件添加对象?
TypeScript条件添加联合类型数组元素的类型错误解决办法
在给类型为FooBar[]的数组使用扩展运算符条件添加元素时,会遇到类型不兼容错误:Types of property 'type' are incompatible 'string' is not assignable to "bar" | "foo"。以下是几种可行的解决思路:
1. 显式锁定字面量类型
TypeScript在条件表达式中会把对象的type推断为宽泛的string,而非字面量'bar'。可以通过as const锁定类型,或者用satisfies确保对象符合接口定义:
interface Foo { type: 'foo'; cool: string; } interface Bar { type: 'bar'; lame: string; } type FooBar = Foo | Bar const arr: FooBar[] = [ { type: 'foo', cool: 'this works great!', }, ...(true && [ { type: 'bar' as const, lame: 'WHY THIS ERROR ON TYPE', } satisfies Bar ]), ]
也可以直接给条件返回的数组标注类型:
...(true && [ { type: 'bar', lame: 'WHY THIS ERROR ON TYPE', } ] as Bar[]),
2. 改用条件push方式
避开扩展运算符的类型推断问题,初始化数组后通过条件判断添加元素:
const arr: FooBar[] = [ { type: 'foo', cool: 'this works great!', }, ]; if (true) { arr.push({ type: 'bar', lame: 'WHY THIS ERROR ON TYPE', }); }
3. 类型断言简化处理
如果能确定元素类型完全符合FooBar,可以直接对条件表达式做类型断言(注意:仅在类型安全的场景下使用,避免滥用):
const arr: FooBar[] = [ { type: 'foo', cool: 'this works great!', }, ...(true && [ { type: 'bar', lame: 'WHY THIS ERROR ON TYPE', } ]) as FooBar[], ]
错误原因
TypeScript在true && [...]这类条件表达式中,会默认将对象的type属性推断为string类型,而不是我们期望的字面量'bar',导致与FooBar联合类型的type约束不匹配。通过上述方式可以强制TypeScript识别正确的字面量类型,解决类型错误。
内容的提问来源于stack exchange,提问作者Mark Rozovsky
相关产品推荐
相关产品推荐

