Microsoft/TypeScript
GitHub ã§èŠãNarrowing `this` using custom type predicate affected by TS 5.0
Open
#53,436 opened on 2023幎3æ22æ¥
BugDomain: This-TypingHelp Wanted
Repository metrics
- Stars
- Â (48,455 stars)
- PR merge metrics
-  (å¹³åããŒãž 6d 17h) (30d ã§ 9 merged PRs)
説æ
Bug Report
ð Search Terms
narrowing this predicate
ð Version & Regression Information
- This changed between versions 4.9 and 5.0
⯠Playground Link
Playground link with relevant code
ð» Code
interface Typestate<TContext extends object> {
value: string;
context: TContext;
}
interface State<TContext extends object, TState extends Typestate<TContext>> {
value: TState["value"];
context: TContext;
matches: <TSV extends TState["value"]>(
value: TSV
) => this is TState extends {
value: TSV;
}
? TState & {
value: TSV;
}
: never;
}
interface Machine<TContext extends object, TState extends Typestate<TContext>> {
initialState: State<TContext, TState>;
}
export declare function createMachine<
TContext extends object,
TState extends Typestate<TContext> = {
value: any;
context: TContext;
}
>(): Machine<TContext, TState>;
const machine = createMachine<{ count: number }>();
const state = machine.initialState;
if (state.matches("idle")) {
((_accept: number) => {})(state.context.count);
// @ts-expect-error
((_accept: string) => {})(state.context.count);
} else if (state.matches("latest")) {
((_accept: number) => {})(state.context.count);
// @ts-expect-error
((_accept: string) => {})(state.context.count);
}
ð Actual behavior
state gets narrowed down to never in the else branch
ð Expected behavior
state to only get narrowed down to the appropriate value within the if branch
cc @ahejlsberg