microsoft / microsoft/TypeScript

Preserve tuples when mapping with `as` clauses

Offen
#40,586 10 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

In Discussion Suggestion
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.3k
Ø Merge
2 T. 4 Std.
Gemergte PRs (30 T.)
132

Beschreibung

Search Terms

#tuple #mapped #as #clause #preserve

Suggestion

New mapped type's as clause allows one to filter the entries of an object. Basic mapped types preserve the shape of a tuple but not when used with the new as clause:

type tuple = [0, 1, 2]

type Mapped<T> = {
    [K in keyof T]: T[K] | undefined
}

type MappedAs<T> = {
    [K in keyof T as K]: T[K] | undefined
}
type test0 = Mapped<tuple>   // tuple shape is preserved
type test1 = MappedAs<tuple> // tuple shape is object now
test0 === [0 | undefined, 1 | undefined, 2 | undefined]
test1 === {
    [x: number]: 0 | 1 | 2 | undefined;
    0: 0 | undefined;
    1: 1 | undefined;
    2: 2 | undefined;
    length: 3 | undefined;
    toString: (() => string) | undefined;
    toLocaleString: (() => string) | undefined;
    ...
}

Use Cases

  • Filtering lists without having to rely on costly recursive types

Examples

type FilterNumbers<T> = {
    [K in keyof T as T[K] extends number ? never : K]: T[K] | undefined
}

type test2 = FilterNumbers<[1, '2', 3, '4']> // ['2', '4']

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

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 damit, die Tupel-Beispiele aus dem Issue in TypeScript nachzustellen, und vergleiche die Ergebnisse von Mapped Types mit und ohne eine as-Klausel. Untersuche die Verarbeitung von Mapped Types durch den Compiler. Füge anschließend Tests hinzu, die zeigen, dass das Filtern eines Tupels dessen Tupelstruktur beibehält, und überprüfe, dass das Beispiel das erwartete gefilterte Tupel erzeugt.

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
25/100

Neue Issues direkt in Ihr Postfach

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