Type narrowing fails when default destructured function argument is provided

1 day ago 3
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' */ } }

Playground

Note: This is similar to a question I previously asked, which had an error where an undefined case was on the b: false option, which made for a nonsensical problem since it would be conflicting which case should be selected when b was not provided.

Read Entire Article