microsoft / microsoft/TypeScript

Partial type for reduce initialValue

Offen
#28,901 6 Kommentare 8 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

reduce initialvalue partial type assertion

Suggestion

Add a signature to the type for Array.reduce<U> to allow the initialValue to be a Partial<U>

Use Cases

Many cases where the reduce function is used to build an object that will eventually conform to U, but starts with an empty accumulator.

Examples

Simple example where the initialValue does not satisfy U but the final result will:

['one'].reduce<{ one: string }>((acc, i) => ({ [i]: i, ...acc }), {})

This yields

Argument of type '{}' is not assignable to parameter of type '{ one: string; }'.
Property 'one' is missing in type '{}' but required in type '{ one: string; }'.

Calling the function without an initialValue causes problems because the initialValue needs to be an object for this to work.

The below type signature would fix this issue:

interface Array<T> {
  reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: Partial<U>): U;
}

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 im Issue beschriebene Signatur von Array.reduce und das Beispiel zu prüfen, in dem ein leeres Objekt als initialValue verwendet wird. Prüfe, wie sich der vorgeschlagene Partial-Parameter auf die Typsicherheit und bestehende reduce-Overloads auswirkt. Als abgeschlossen gilt die Aufgabe, wenn der Vorschlag mit einem abgestimmten Typ-System-Entwurf und der entsprechenden Validierung geklärt ist.

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.