Microsoft/TypeScript
Auf GitHub ansehenInferred type for accumulator and return value of `Array#reduce` is incorrect when used with `Record<string, unknown>`
Open
#59.196 geöffnet am 9. Juli 2024
Domain: check: Type InferenceHelp WantedPossible Improvement
Repository-Metriken
- Stars
- (48.455 Stars)
- PR-Merge-Metriken
- (Durchschn. Merge 6T 17h) (9 gemergte PRs in 30 T)
Beschreibung
🔎 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