microsoft / microsoft/TypeScript
TypeScript cannot always infer the correct type through a user-defined type guard using the 'is' operator.
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.3k
- Ø Merge
- 1 T. 19 Std.
- Gemergte PRs (30 T.)
- 117
Beschreibung
🔎 Search Terms
"typeguard", "is operator"
🕗 Version & Regression Information
Tested with typescript@5.1.3 and later
⏯ Playground Link
No response
💻 Code
enum kind {
a = 'a',
b = 'b',
c = 'c'
}
type ID = {
id: number
}
class Test<T extends kind> {
value: T extends kind.a | kind.b ? ID : undefined
type: T
constructor(
type: T,
value: T extends kind.a | kind.b ? ID : undefined
) {
this.type = type
this.value = value
}
hasID(): this is Test<Exclude<kind, kind.c>> {
return this.type !== kind.c
}
do() {
if (this.hasID()) {
return this.value.id // Error: this.value: Object is possibly 'undefined'
// return (this as Test<Exclude<kind, kind.c>>).value.id // this works
}
}
}
🙁 Actual behavior
TypeScript cannot infer that 'this' is of type 'Test<Exclude<kind, kind.c>>' even though there is a type guard. In the 'do' method, TypeScript throws a TSError stating that 'this.value': Object is possibly 'undefined'.
If we explicitly cast 'this' as 'Test<Exclude<kind, kind.c>>', we can access the 'value' attribute, and it works as it should. However, somehow the type guard does not have the same effect.
🙂 Expected behavior
Since there is a type guard around the 'this.value.id' line, TypeScript should handle 'this' as a 'Test<Exclude<kind, kind.c>>' type. At least, that's what type guards are for in my understanding.
Additional information about the issue
No response
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 mit der bereitgestellten TypeScript-Reproduktion und verfolge, wie der Typprüfer this nach dem benutzerdefinierten Type Guard hasID() eingrenzt. Füge einen Compiler-Regressionstest für den erwarteten Zugriff auf this.value.id hinzu und überprüfe anschließend, dass die Diagnose entfernt wird, ohne die Prüfungen für den Fall kind.c abzuschwächen.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- typescript
- Bereich
- compilers
- Issue-Typ
- Bug
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 25/100