Repository navigation
Closed
Labels
Design LimitationConstraints of the existing architecture prevent this from being fixed
Description
TypeScript Version: 3.6.3
Search Terms:
array.map, expression is not callable, union type signatures,
Code
The following code is the exact same code as in this codesandbox
https://codesandbox.io/s/lingering-sun-7itgj
interface Product_result {
__typename: 'Product'
id: number
description: string | null
}
interface Campaign_result {
__typename: 'Campaign'
id: number
products: (Product_result | null)[] | null
}
interface Product {
id: number
description: string
specific: boolean
}
interface Campaign {
products: Product[]
}
type CompoundType = Campaign_result | Campaign
/* --- */
const props: { campaign?: Campaign_result } = {}
const emptyCampaign: Campaign = {
products: []
}
const initialData: CompoundType = props.campaign || emptyCampaign
/*
Cannot invoke an expression whose type lacks a call signature. Type '
(<U>(callbackfn: (value: Product_result, index: number, array: Product_result[]) => U, thisArg?: any) => U[])
| (<U>(callbackfn: (value: Product, index: number, array: Product[]) => U, thisArg?: any) => U[])
' has no compatible call signatures.
product inside map is any, but I know `id` is there
*/
initialData.products.map(product => product.id)
// product is { description: string, id: number } - as expected
const product = initialData.products[0]
// product inside map is { description: string, id: number } - as expected
;(initialData.products as Array<CompoundType['products'][0]>).map(product => product.id)
/* interestingly */
type T01 = Array<CompoundType['products'][0]> // T01: (Product_result | Product)[] - I can actually have mix of both. Products that were fetched and Products added via a Form
type T02 = CompoundType['products'] // T02: Product_result[] | Product[]
declare const v1: T01
v1.map(product => product) // OK
declare const v2: T02
v2.map(product => product) // NOKExpected behavior:
I know id is there, so this should work
initialData.products.map(product => product.id)
This workaround works
(initialData.products as Array<CompoundType['products'][0]>).map(product => product.id)
Actual behavior:
The map gives a non compatible call signature error (as in the snippet above), and the product inside is any.
Related
TypeScript 3.3 - Improved behavior for calling union types
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-3.html#caveats
Reacted by WhizSid, vavra7, Wilk, Alexey, Vincent, yurii, Andreas, Lucas Caton, ali, 流浪大法师 and 13 more
Metadata
Metadata
Assignees
Labels
Design LimitationConstraints of the existing architecture prevent this from being fixed
Activity
jack-williams commentedon Sep 25, 2019
I think this is being tracked here #7294.
RyanCavanaugh commentedon Sep 25, 2019
We don't have any way to check this in a way that's well-bounded in terms of analysis time.
Consider if you had written something like this:
The only way to correctly check this program is to re-check the body of the inner body 3 * 3 * 3 times (!), and TS would need to clear its cache of expression types on each invocation (something which is currently architecturally impossible). It's not even clear what we'd show for
arr's type here!A typical suggestion is some sort of merging of argument types into unions, but this only works in some cases (it's OK for
mapbut doesn't make sense forfilter, for example).ackvf commentedon Sep 30, 2019
I see, that's understandable. So, is there an official best-practice™ workaround for this or should I resort to manually extract the types like this?
whizsid commentedon Mar 27, 2020
I have solved in that way.
Edit: Supress TS error
Ranguna commentedon May 9, 2020
I'm probably missing something here, but to me
arrwould be[string | number | boolean, string | number | boolean, string | number | boolean]. This would fail to compile because the first parameter offndoesn't accept abooleanvalue.I think #29011 solved exactly that and #31023 should solve remain issues with function overloads (such as
.map).Fleuv commentedon May 25, 2020
I also experienced this issue with the following use case.
TypeScript Version: 3.9.2
Code
Playground Link
matAtWork commentedon Jun 10, 2020
And here's another really simple illustration:
Note that
forEachworks here, so with a closure & a little refactor, you can make this work in practicejeje42 commentedon Aug 10, 2020
Hi, I also have the same problem as Random bug (@Fleuv) here with typescript 3.9.7. Can I ask what is the status of this issue and why it is closed ?
AndyOGo commentedon Jan 21, 2021
Same Problem here with
Array.prototype.find()SephReed commentedon Feb 26, 2021
tl;dr: to get around this issue -> flatten your types to fit through whichever generic is the pigeon-hole, then use "type predicates" to make them whole again
Understanding the Problem
Alright, so after poking around for a bit, I've come to figure out what the heck is going on.
Basically
(Array<Foo | Bar>)and(Foo[] | Bar[])are very different things as far as typescript is concerned:Typescript Playground Demo Link
Subjective Digression
So, obviously this is kind of ridiculous. As far as any developer is concerned, it would be good enough to be able to map
cannotMapand get slightly false typing on the items as(item: Foo | Bar) => any. In reality, the function should be((item: Foo) => any) | ((item: Bar) => any)..... whew! really saving us from ourselves!And -- unfortunately -- I've seen enough CLOSED typescript issues to know that this is never going to be changed. It's pedantic and dumb, so they'll say it's for the sake of not being inaccurate. Then on some other issue they'll shirk the whole "preserve runtime behavior of all JavaScript code" accuracy thing, and say that being an actual superset of javascript is too pedantic. So we're just going to have to work around this one.
The Fix
This sucks, BUT: the best way to fix this issue is to just flatten your types, then create type checkers to turn them back into what they're suppose to be. Something like the following:
Typescript Playground Link
It's a super ugly solution in practice. You have to flatten entire complex types into something that never realistically exists just so it'll fit through the pigeonhole that is
ts(2349). But it works, so be it.Subjective Suggestion
I don't expect anyone with sway to be reading this, but on the off-chance such a thing should happen, I have a suggestion for making everyone happy; something like this:
Pretty self explanatory, but for completenesses sake:
Array<Foo | Bar>being usable, while(Foo[] | Bar[])is totally brokenAnd even though this isn't perfectly accurate, it being accurate wouldn't really change the way anyone codes AFAICT. Either way you're going to have to check types. And given that the current way things are you can't even get to the point of checking types, it's not really helping anyone.
So why not give us the option to be able to move forwards at a tiny fraction of loss of accuracy? Surely that's better than everyone having to cannibalize their types just to put them back together on the other side of this error.
Hope this helps someone. <3
luisanton-io commentedon May 16, 2021
I had an array
fooof type A[] or B[].When
mapping it, this error was showing up.I had to declare
and then map
_foo.Thank you so much!
bombillazo commentedon Jul 5, 2022
Luis Antonio Canettoli Ordoñez (@luisanton-io) Marvelous! That worked for me.
aiham commentedon Oct 20, 2023
For my use case
(A | B)[]and(A[] | B[])are equivalent so I was happy to workaround it with:This way the types remain inferred from
generateVariousItemsinstead of redefining them.scffs commentedon Jan 31, 2024
I was really surprised when I fix this error by replace
A[] | B[]withArray<A | B>nicknish commentedon Feb 8, 2024
Hey folks, stumbled upon the same issue. I believe this is fixed in TypeScript 5.2:
https://devblogs.microsoft.com/typescript/announcing-typescript-5-2/#easier-method-usage-for-unions-of-arrays
tejas-1206 commentedon May 15, 2025
But how ? How is
Array<A | B>different thanA[] | B[]? DoesArray<A> | Array<B>work ?luisanton-io commentedon May 16, 2025
Yes, they are indeed different types.