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
TypeScript should infer Exclude types in conditional expressions and statements.
Specifically, whenever the positive branch (if, or the x in c ? x : y) has a more specific type thanks to a type guard, the negative branch (else/y) should have the relevant Exclude type.
Use Cases
This would provide a natural way to infer Exclude types and it would generalise in a natural way the current behaviour of conditional statements over union and finite-domain types.
Apparently right now the only way to have a value of type Exclude is to assert it manually (either through type guards or type assertions).
Examples
functionpartition<A,BextendsA>(items: A[],f: (x: A)=>x is B): [B[],Array<Exclude<A,B>>]{constbs: B[]=[];constothers: Array<Exclude<A,B>>=[];for(constxofitems){if(f(x)){bs.push(x);}else{// with the proposed feature, x: Exclude<A, B> in this branchothers.push(x);// while currently this fails because TSC infers x: A}}return[bs,others];}
Notice that this is consistent with the fact that the positive branch infers the Extract type (already resolved to the non-never type, thanks to the constraints on type guards).
I built #22348 locally and the example above fails to compile with the same error: error TS2345: Argument of type 'A' is not assignable to parameter of type 'Exclude<A, B>'.
This issue is likely a duplicate of #23764, but while that was a bug report (and thus closed as "not a bug"), this is a feature request, proposing an improvement to type narrowing.
Activity
ajafff commentedon Jan 6, 2019
This should be covered by #22348
ranma42 commentedon Jan 6, 2019
Possibly a duplicate of #23764
ranma42 commentedon Jan 7, 2019
Notice that this is consistent with the fact that the positive branch infers the
Extracttype (already resolved to the non-nevertype, thanks to the constraints on type guards).weswigham commentedon Jan 7, 2019
#22348 would be what this needs, yeah. Conditional types still have a few problems that make the current behavior by-design, though 😦
ranma42 commentedon Jan 8, 2019
I built #22348 locally and the example above fails to compile with the same error:
error TS2345: Argument of type 'A' is not assignable to parameter of type 'Exclude<A, B>'.weswigham commentedon Jan 8, 2019
PR isn't quite fully done (it has issues as-is). It doesn't swap control flow to using extract/exclude yet afaik.
typescript-bot commentedon Jan 10, 2019
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.
ranma42 commentedon Jan 11, 2019
This issue is likely a duplicate of #23764, but while that was a bug report (and thus closed as "not a bug"), this is a feature request, proposing an improvement to type narrowing.