Microsoft/TypeScript
Ver no GitHubInferred type for accumulator and return value of `Array#reduce` is incorrect when used with `Record<string, unknown>`
Open
#59.196 aberto em 9 de jul. de 2024
Domain: check: Type InferenceHelp WantedPossible Improvement
Métricas do repositório
- Stars
- (48.455 stars)
- Métricas de merge de PR
- (Mesclagem média 6d 17h) (9 fundiu PRs em 30d)
Description
🔎 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