Home > database >  Why TypeScript complains about Array.from(somethingPotentiallyUndefined || []) statement?
Why TypeScript complains about Array.from(somethingPotentiallyUndefined || []) statement?

Time:04-26

enter image description here

Can you help me understand the following compiler error?

When I initialize the model to either undefined or [] in that code, the error goes away. When I leave the model implicitly undefined, like in the screenshot, I get an error.

CodePudding user response:

It doesn't complain about somethingPotentiallyUndefined.

It complains about somethingPotentiallyNumber.

TypeScript disallows to invoke Array.from with a number, as in

Array.from(42)

In your case, model can be GridInputSelectionModel, which can be GridRowId, which in turn can be number, which is bad.

The error goes away if you explicitly set model to undefined, because the flow sensitive type inference can figure out that at that specific location model can be only undefined, so that the argument to Array.from is guaranteed to become [], which, unlike a number, is valid.

CodePudding user response:

The problem is that GridInputSelectionModel is potentially not iterable. If you don't assing "undefined" TypeScript does not know which type model has (both would have to be iterable). Is it GridInputSelectionModel or undefined?

By assigning undefined you answer the question.

Because undefined || [] (which you explicitly stated) is []. The error goes away because "[]" is iterable. However, this has nothing to do with your model variable anymore you would always pass an empty array.

  • Related