TypeScript带默认函数参数时类型收窄失效问题排查
TypeScript带默认值的解构参数无法触发类型收窄问题
使用TypeScript v6.0.3(也测试过v4.9.5及更早版本)时,对以对象形式传入的函数选项进行类型收窄,发现带有默认值的参数无法正常触发TypeScript的自动类型判别。
为什么fun1的if代码块中无法将t的类型收窄为仅string(仍显示为string|number),而fun2却能根据类型定义正确收窄类型?这是TypeScript的bug吗?
type Type = { b?: false, t: number, } | { b: true, t: string, } // 无法正常收窄 function fun1({b = true, t}: Type) { if(b) { t /* <-- 无法识别为仅string,类型为string|number */ } } // 可以正常收窄 function fun2({b, t}: Type) { if(b) { t /* <-- 可识别为string */ } }
注:有用户指出本问题存在错误,undefined情况应归属于b: true的分支而非b: false的分支。我已提交修正后的问题,展示了实际问题(由@MattKantor在评论中指出)
内容的提问来源于stack exchange,提问作者mwsundberg
相关产品推荐
相关产品推荐

