Microsoft/TypeScript
GitHub ã§èŠãNarrowing by type predicate fails to produce intersection type with weak type
Open
#58,518 opened on 2024幎5æ13æ¥
BugDomain: check: Control FlowHelp Wanted
Repository metrics
- Stars
- Â (48,455 stars)
- PR merge metrics
-  (å¹³åããŒãž 6d 17h) (30d ã§ 9 merged PRs)
説æ
ð Search Terms
- predicate
- intersection
- weak
ð Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________
⯠Playground Link
ð» Code
interface A {
label?: string;
a?: string; // make required to eliminate error
}
interface B {
label?: string; // remove shared property to eliminate error
b: boolean;
}
function isB(thing: object): thing is B {
return 'b' in thing;
}
function test(thing: A) {
thing.a; // ok
if (isB(thing)) {
thing.a; // error?
}
}
ð Actual behavior
The type of thing inside the conditional is B.
ð Expected behavior
The type of thing inside the conditional should be A & B.
Additional information about the issue
This only happens if:
Ais a "weak" type (all optional properties).AandBhave at least one overlapping property.
If either of these isn't the case, then you get the expected intersection type:
This came up in vscode while testing https://github.com/microsoft/TypeScript/pull/58495#issuecomment-2105358748. The issue is there already but is latent because control flow analysis can't see that a type predicate becomes a type assertion without that PR.