microsoft / microsoft/TypeScript

`asserts this is T` does not narrow type of `this`

Open
#60,140 11 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Cursed? Domain: This-Typing Possible Improvement
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

🔎 Search Terms
  • asserts this is T
  • narrow
  • assertions
  • I also checked #59707, but it is unrelated (generic types).
🕗 Version & Regression Information
  • Playground: v5.7.0-dev.20241004
  • At least since v5.6.2
⏯ Playground Link

https://www.typescriptlang.org/play/?#code/MYGwhgzhAECC0G8BQ1oHsB2ICeARApgGYCWG+AJgJIawAUAlIiqtMJhGiPgHQhoDmtAESwh9ANzMAvkmaQI+AE4AXOvQBc0eUuUxlAC2IwjcRNBkzZoedABCTVNpVrNT3dAMmT8BOaSXlbAAHfGgAYWgAXlMAHztJJEIAVwxgZWJMLSgdOmBNMI0shRUYYGhvJktk1PTM5XwIZQBGWjzwxmRUYG43NUku7kwcAhIyKhoGcWgAemnoAFFFRTRFTQAFZZCVbGgAciG8IlIKalhd6HI0BugMNGVofAAPI3u64NDdsN3uaA20LcCewOI2O4zOFyuMFu9yeL3QGA87z2tm+-lk1TSGQR9UaACZWvkOnJss5WhJmN1gUcxqdJjM5gB1FYAawgAEI0dAgA

💻 Code
class A {
  onlyDefinedInA() {
    console.log("A");
  }

  assertA(): asserts this is A { }
}


class B {
  assertA(): asserts this is A { }
}

type C = A | B;

function assertA(c: C): asserts c is A {
}

function test1(c: C) {
  c.assertA();
  c.onlyDefinedInA(); // Error: Property 'onlyDefinedInA' does not exist on type 'C'. Property 'onlyDefinedInA' does not exist on type 'B'.
}

function test2(c: C) {
  assertA(c);
  c.onlyDefinedInA(); // Works!
}

Workbench Repro

🙁 Actual behavior

Type of c is not narrowed after the method call, producing an error.

🙂 Expected behavior

I expect the member function to to perform type narrowing.

Additional information about the issue

No response

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 TypeScript Playground repro and compare the method-call case in test1 with the standalone assertion in test2. Trace how asserts this is A is handled after a member call, then verify that the method call narrows c so onlyDefinedInA() is accepted without regressing the standalone case.

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
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.