microsoft / microsoft/TypeScript

flatMap errors when callback returns certain union types

Open
#31,033 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the TypeScript 3.4.3 example with strict null checks enabled, comparing flatMap(mapFn) with the separate map and flat calls. Trace the library definition and type-checking behavior for callbacks returning number[] | undefined; done means the reported example accepts the callback and infers (number | undefined)[] as expected.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.