Typescript: Array element type inference not working in array methods when array is union type

Created on 3 Sep 2020  路  4Comments  路  Source: microsoft/TypeScript



TypeScript Version: 4.1.0-dev.20200903


Search Terms:
Union array type element inference in methods
Code

type Unpack<T> = T extends ReadonlyArray<infer P> ? P : never;

const test: ['a', 'b'] | ['c', 'd'] = ['a', 'b'] as any;

test.forEach(el => el); //error: Parameter 'el' implicitly has an 'any' type
test.forEach((el: Unpack<typeof test>) => el);
const element = test[1];

Expected behavior:
Both forEach calls should infer col in the same way: el should be 'a' | 'b' | 'c' | 'd'
Actual behavior:
First call can't infer el type.

Playground Link:
https://www.typescriptlang.org/play?ts=4.1.0-dev.20200903#code/C4TwDgpgBAqgdmAhgYwNYB4AqA+KBeKTKCAD2AjgBMBnKAJQkUoHs4AbEAQQCdvER0ASzgAzCNygAFXAH4pUAFxQ4EAG7iA3ACgtyVtWBRyBpQG0A5InMAaKOYBG5gLpQAPlAvIbdys-wfLbwc-RFpEOBBtLWNgADoRZm4AURQACwAKCDZ8XCyASm0Y+MSU5AzMtiV4JDR0UEhmESMIA2w8nOI2At19QyyIAFsKQwIY0wBGJw0gA
Related Issues:

All 4 comments

I don't get This expression is not callable error, for me it's just el is inferred as any.

@IvanZatravkin A closer duplicate would be #34605.

Looks like it, thanks

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Antony-Jones picture Antony-Jones  路  3Comments

Roam-Cooper picture Roam-Cooper  路  3Comments

jbondc picture jbondc  路  3Comments

bgrieder picture bgrieder  路  3Comments

CyrusNajmabadi picture CyrusNajmabadi  路  3Comments