microsoft / microsoft/TypeScript

Extend type predicate inference to work with certain type variables

Offen
#59,088 3 Kommentare 1 Reaktion 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

type predicate inference generic

✅ Viability Checklist
⭐ Suggestion

When a function would normally serve as a type predicate for a discriminated union, but the exact cases being selected by the type predicate are dictated by a type variable, it'd be nice if the type predicate could still be inferred.

📃 Motivating Example
type Thing = A | B | C
type A = { kind: 'A', id: string, /* ... */ }
type B = { kind: 'B', id: string, /* ... */ }
type C = { kind: 'C', id: string, /* ... */ }

function filterByKind<T extends Thing['kind']>(things: Thing[], kind: T) {
  return things.filter((it) => it.kind === kind);
}

// The below would ideally be typed as `A[]`, as the function passed to 
// `filter` would have an inferred type predicate of `it is Thing & { kind: T }`
const x = filterByKind([], 'A');

const someKind = Math.random() < .5 ? 'A' : 'B';
const y = filterByKind([], someKind); // (A | B)[]
💻 Use Cases

I think this comes up somewhat rarely, and the workaround is to simply manually write out the generic type predicate, but, at my company, we did find cases like this when we looked at our type predicates as part of upgrading to TS 5.5

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

Im Issue werden keine Implementierungsdateien, Tests oder Einstiegspunkte genannt. Beginne damit, die motivierenden Beispiele zu reproduzieren, und untersuche das bestehende Verhalten bei der Inferenz von Typprädikaten. Als erledigt gilt die Aufgabe, wenn die generischen filterByKind-Beispiele für 'A' A[] und für eine Vereinigung von Arten (A | B)[] inferieren, ohne die Laufzeitausgabe zu ändern.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
typescript
Bereich
compilers
Issue-Typ
Feature
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
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.