microsoft / microsoft/TypeScript
`asserts this is T` does not narrow type of `this`
Open
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 Tnarrowassertions- 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
💻 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!
}
🙁 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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