ARTICLE AD BOX
Using TypeScript v6.0.3 (also tested on earlier versions down to v4.9.5), I'm narrowing the type for the options of a function which are passed as an object. Some of those parameters have default values. The parameters which have default values aren't working properly with TypeScript automatic type discernment, as far as I can tell.
Why does fun1 fail to narrow the type of t in the if block, yet fun2 can properly narrow its type based on the definition? Is this a bug?
type Type = { b?: false, t: number, } | { b: true, t: string, } // This doesn't work function fun1({b = true, t}: Type) { if(b) { t /* <-- can't discern type as 'string' only, is 'string|number' */ } } // This works function fun2({b, t}: Type) { if(b) { t /* <-- can discern type as 'string' */ } }124k31 gold badges287 silver badges493 bronze badges
3
