TypeScript为何判定我的类型可能为undefined?
TypeScript联合元组类型收窄的限制问题
先看你的代码:
type Props = {a: number} type FuncSig = [string, Props] | [Props] function thing(...props: FuncSig) { const {a} = typeof props[0] === 'string' ? props[1] : props[0] }
编译器报错:
Property 'a' does not exist on type 'Props | undefined'.
原因分析
TypeScript的控制流分析不支持对元组联合类型做跨元素的关联类型收窄。具体来说:
FuncSig是两个元组的联合:[string, Props]或[Props]- 当你检查
typeof props[0] === 'string'时,编译器只能确定props[0]是string,但无法推断出props整体属于[string, Props]这个分支。因此,props[1]的类型会被判定为Props | undefined——因为另一个分支[Props]没有第二个元素,访问索引1会得到undefined。 - 在else分支中,编译器同样无法把
props的类型收窄到[Props]分支,虽然逻辑上props[0]不可能是string,但编译器不会自动关联元组的整体类型,导致整个三元表达式的结果类型被合并为Props | undefined。 - 最后解构
{a}时,TypeScript认为这个值可能是undefined,自然会报错说a属性不存在。
可选解决方法
如果要让编译器正确识别类型,可以手动通过类型守卫收窄整个props的类型:
function isStringPropsTuple(props: FuncSig): props is [string, Props] { return typeof props[0] === 'string'; } function thing(...props: FuncSig) { const target = isStringPropsTuple(props) ? props[1] : props[0]; const {a} = target; // 此时target类型确定为Props,无报错 }
内容的提问来源于stack exchange,提问作者Mild Fuzz
相关产品推荐
相关产品推荐

