microsoft / microsoft/TypeScript

Narrowing `this` using custom type predicate affected by TS 5.0

Open
#53,436 5 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: This-Typing Help Wanted
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked Playground repro and compare its narrowing behavior between TypeScript 4.9 and 5.0. Investigate the type-checking path for custom predicates on this, then verify that the if and else branches narrow to appropriate states and the included @ts-expect-error checks pass.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.