microsoft / microsoft/TypeScript
Allow this in type guards when type of this is explicitly specified in method signature
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Search Terms
"A 'this' type is available only in a non-static member of a class or interface.(2526)" guard
Relevant: #37796 (but this one is different)
Suggestion
Remove error 2526 in guard condition if type of this is specified explicitly using this: SomeType.
Since both guard condition and method body work as expected, I assume only the error check needs to be removed.
Use Cases
Defining a guard without having a class (have some cases where full class would be an overkill).
Examples
({
guard(this: { x?: 1 }): this is { x: 1 } {
return this.x === 1;
}
})
Note that this is not any and works perfectly fine in both the method body and the guard:
const o = ({
x: 1 as 1|2,
guard(this: { x: 1 | 2 }): this is { x: 1 } {
// body works
return this.x === 1;
}
});
if (o.guard()) {
// guard works
const check: 1 = o.x;
}
Would be good to support guard in ThisType<> as well (see #37796), but can be a separate thing.
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
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 by reproducing error 2526 with the object-literal guard examples in the TypeScript Playground, then trace the type-checking path for an explicit this: SomeType method signature and its guard condition. Done means the diagnostic is removed for this case, both examples type-check as shown, and the existing behavior for invalid this usage remains unchanged.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100