-
Notifications
You must be signed in to change notification settings - Fork 13k
Open
Labels
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScriptAn idea for TypeScript
Description
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.
mjwwit, jaredLunde, caleb15, WeshGuillaume, nickbreaton and 3 more
Metadata
Metadata
Assignees
Labels
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScriptAn idea for TypeScript