You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
interfaceA{hasValue: true;value: string;}interfaceB{hasValue: false;}functioncheckOne(args: A|B){returnargs.hasValue&&args.value;// ^^^^^ this is ok, 'args' infers type A}functioncheckTwo(args: A|B){const{ hasValue }=args;returnhasValue&&args.value;// ^^^^^ Error: Property 'value' does not exist on type 'B'.}
Expected behavior:
Both checkOne and checkTwo compiled without errors.
Actual behavior:
Function checkTwo has compilation errors.
It does not "lose" type inference, the type inference just does not work the way you expect it. You're not checking args.hasValue (which would narrow the type to A), you're checking hasValue. The TypeScript compiler does not make the connection "hasValue comes from args, so by checking hasValue I can narrow args". It's unrelated to the destructuring, you have the same issues if you just assign it to a variable: const hasValue = args.hasValue.
There are numerous issues about this exact issue, that the type narrowing is not tracked across variables.
TypeScript Version: 3.1.1
Search Terms:
Code
Expected behavior:
Both
checkOne
andcheckTwo
compiled without errors.Actual behavior:
Function
checkTwo
has compilation errors.Playground Link: typescriptlang.org
Related Issues: I can't find related issues, but I am sure this is already known issue.
The text was updated successfully, but these errors were encountered: