Microsoft/TypeScript
Vedi su GitHubInferred type for accumulator and return value of `Array#reduce` is incorrect when used with `Record<string, unknown>`
Open
#59.196 aperta il 9 lug 2024
Domain: check: Type InferenceHelp WantedPossible Improvement
Metriche repository
- Star
- (48.455 star)
- Metriche merge PR
- (Merge medio 6g 17h) (9 PR mergiate in 30 g)
Descrizione
🔎 Search Terms
"array reduce unknown"
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about
Array#reduce
⏯ Playground Link
💻 Code
/**
* Reducing an array of records with string values
*/
namespace ExampleA {
const array = [] as Record<string, string>[]
const reduced = array.reduce((acc) => acc, {} as Record<string, number>)
reduced // Type is correct (Record<string, number>)
}
/**
* Same as ExampleA except with an array of records with unknown values
*/
namespace ExampleB {
const array = [] as Record<string, unknown>[]
const reduced = array.reduce((acc) => acc, {} as Record<string, number>)
reduced // Type is NOT correct (should be Record<string, number>)
}
/**
* Same as ExampleB except accumulator is cast to an object type with an index signature instead of record
*/
namespace ExampleC {
const array = [] as Record<string, unknown>[]
const reduced = array.reduce((acc) => acc, {} as { [key: string]: number })
reduced // Type is NOT correct (should be { [key: string]: number })
}
/**
* Same as ExampleB except with an array of an object type with an index signature instead of record
*/
namespace ExampleD {
const array = [] as { [key: string]: unknown }[]
const reduced = array.reduce((acc) => acc, {} as Record<string, number>)
reduced // Type is NOT correct (should be Record<string, number>)
}
/**
* Same as ExampleB except accumulator is cast to a number instead of record
*/
namespace ExampleB {
const array = [] as Record<string, unknown>[]
const reduced = array.reduce((acc) => acc, {} as number)
reduced // Type is correct (number)
}
🙁 Actual behavior
Inferred type of accumulator and return value of Array#reduce is Record<string, unknown> in the provided examples.
🙂 Expected behavior
Inferred type of accumulator and return value of Array#reduce should be based on the type of the initial value.
Additional information about the issue
No response