microsoft / microsoft/TypeScript
Inferred type for accumulator and return value of `Array#reduce` is incorrect when used with `Record<string, unknown>`
オープン
まだ誰も着手していません。
Domain: check: Type Inference
Help Wanted
Possible Improvement
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.4k
- 平均マージ
- 1日 19時間
- マージ済み PR(30日)
- 117
説明
🔎 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
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
リンクされている TypeScript Playground から始め、Examples A–D における Array#reduce の型推論を比較し、アキュムレーターと初期値の型に焦点を当てます。Record<string, unknown> とインデックスシグネチャ配列の動作を確認し、続いて、期待される動作に示されているとおり、アキュムレーターと戻り値の型が初期値に基づいていることを検証します。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- typescript
- 領域
- compilers
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- 明確に書かれている
- 初心者へのやさしさ
- 45/100