microsoft / microsoft/TypeScript

Allow conditionally setting optional properties in a mapped type

Offen
#36,126 8 Kommentare 15 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

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

Beschreibung

Search Terms

conditional optional mapped type

Suggestion

Allow us to conditionally apply ? to a property in a mapped type

Use Cases

I have a function:

function myFunction(one: string, two: number, three: number){}

but I want to map the params to

function myFunction(one: string, two?: number, three?: number){}

Examples

Suggested approach:

type MapParams<T> = {
    [P in keyof T]: T[P] extends string ? T[P] : | ?T[P]
}

(or something similar)

This is the closest I could come:

type MapParams<T> = {
    [P in keyof T]: T[P] extends string ? T[P] : | T[P] | undefined
}

but that produces

function myFunction(one: string, two: number | undefined, three: number | undefined){}

myFunction("", undefined, undefined)

Playground

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

Das Issue enthält keine Implementierungsdateien oder Tests; beginne mit dem verknüpften Playground und den Beispielen für mapped types. Die Fertigstellung bedeutet, eine Möglichkeit zu unterstützen, ausgewählte mapped properties bedingt optional zu machen und ausgelassene properties von properties zu unterscheiden, die explizit auf undefined gesetzt wurden, wobei Compiler-Tests die gezeigte Form der Funktion abdecken.

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.