Search code examples
arraystypescripttypeerror

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


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.


Solution

  • 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.