microsoft / microsoft/TypeScript

Type predicate for an optional property is not inferred

Offen
#59,494 6 Kommentare 2 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Awaiting More Feedback Suggestion
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.4k
Ø Merge
1 T. 19 Std.
Gemergte PRs (30 T.)
117

Beschreibung

🔎 Search Terms

inferred type predicate optional

🕗 Version & Regression Information
  • This changed between versions 5.4 and 5.5
⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.5.4#code/C4TwDgpgBA8gRgKygXigbwPZmASwwOwEMAbAfgC51DL8BXAWzggCcBfVgKFElkQCYU6LLgIkKUWvgAmEAGY58EKaygAfIdjxFilNNSh1GLdh1OzJAYxH4oOAM4xNo4gBE5CpQAoIleAgCU6BwA9MFQ4RFQAHqkHJHMEMC0zDYQAHTCWiRQAITIqJIy8opSHJwc5vhWWrYOTtpuxUp83r78gWghYTFxEQlJKVDpmc65+RLS7iVlHEA

💻 Code
type Obj = {optional?: {a: number}}

function isOptionalDefined(e: Obj) {
    return e.optional !== undefined
}

if (isOptionalDefined(someObj) {
  someObj.optional.a // 'someObj.optional' is possibly 'undefined'
}
🙁 Actual behavior

If a type contains an optional property, and I write a function that ensures the property is defined, the function is not inferred as a type predicate. No type narrowing happens when I use this function.

At the same time, if I rewrite the original type to be itself a union, then the type predicate is inferred, as expected.

🙂 Expected behavior

Type predicate is inferred

Additional information about the issue

I feel it has something to do with https://github.com/microsoft/TypeScript/issues/55257, but I'm not sure.

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne mit der im Issue verlinkten TypeScript Playground-Reproduktion und vergleiche das Verhalten von 5.4 und 5.5 für das Prädikat für optionale Eigenschaften. Lies die Diskussion in Issue #55257 für den entsprechenden Kontext; fertig ist die Aufgabe, wenn das Prädikat inferiert wird und die optionale Eigenschaft im bereitgestellten Beispiel ohne Fehler eingegrenzt wird.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
typescript
Bereich
compilers
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.