microsoft / microsoft/TypeScript
Allow this in type guards when type of this is explicitly specified in method signature
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.4k
- Ø Merge
- 1 T. 19 Std.
- Gemergte PRs (30 T.)
- 117
Beschreibung
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.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne damit, error 2526 mit den Guard-Beispielen für Objekt-Literale im TypeScript Playground zu reproduzieren, und verfolge dann den Type-Checking-Pfad für eine explizite Methodensignatur this: SomeType und ihre Guard-Bedingung. Erledigt ist die Aufgabe, wenn die Diagnose für diesen Fall entfernt wurde, beide Beispiele wie gezeigt typgeprüft werden und das bestehende Verhalten für ungültige this-Verwendung unverändert bleibt.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- typescript
- Bereich
- compilers
- Issue-Typ
- Feature
- Schwierigkeit
- 3/5
- Geschätzter Aufwand
- 1-2 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100