Microsoft/TypeScript
GitHub ã§èŠãInferred type for accumulator and return value of `Array#reduce` is incorrect when used with `Record<string, unknown>`
Open
#59,196 opened on 2024幎7æ9æ¥
Domain: check: Type InferenceHelp WantedPossible Improvement
Repository metrics
- Stars
- Â (48,455 stars)
- PR merge metrics
-  (å¹³åããŒãž 6d 17h) (30d ã§ 9 merged PRs)
説æ
ð 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