microsoft / microsoft/TypeScript
flatMap errors when callback returns certain union types
まだ誰も着手していません。
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.4k
- 平均マージ
- 1日 19時間
- マージ済み PR(30日)
- 117
説明
TypeScript Version: 3.4.3
Search Terms: flat, flatmap
Code
// Map<string, number[]>
const myMap = new Map([
['foo', [1, 2, 3]],
['bar', [4, 5, 6]]
]);
// string[]
const myArray = ['foo', 'bar', 'baz'];
// (key: any) => number[] | undefined
const mapFn = key => myMap.get(key);
const flatMapped = myArray.flatMap(mapFn);
Actual behavior:
With strict null checks on:
Argument of type '(key: any) => number[] | undefined' is not assignable to parameter of type '(this: undefined, value: string, index: number, array: string[]) => number | readonly number[]'.
Type 'number[] | undefined' is not assignable to type 'number | readonly number[]'.
Type 'undefined' is not assignable to type 'number | readonly number[]'. ts(2345)
Turning strict null checks off prevents the error as you might expect, but that's obviously not desirable.
More generally, any callback that returns foo[] | bar (where bar is not compatible with foo) seems to run into the same issue. The Map.prototype.get example I've used here just seems like it would be a relatively common use case in particular (you'd typically follow it up by calling .filter(Boolean) or similar on the mapped result).
More code
Seeing if doing the operations separately will help:
// (number[] | undefined)[]
const mapped = myArray.map(mapFn);
// any[] !!
const flattened = mapped.flat();
Expected behavior:
flatMapped/flattened result to be inferred as (number | undefined)[].
Playground Link:
Doesn't seem to be able to load the appropriate library definition, even with /// <reference lib="es2019.array" />
Related Issues:
#29604 seems to be related to the .flat() part.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
strict null checks を有効にした TypeScript 3.4.3 の例を再現し、flatMap(mapFn) と map および flat を別々に呼び出す場合を比較する。number[] | undefined を返すコールバックについて、ライブラリ定義と型チェックの挙動を追跡する。報告された例がコールバックを受け入れ、期待どおり (number | undefined)[] を推論すれば完了とする。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- typescript
- 領域
- compilers
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100