TERNARY TYPES IN TYPESCRIPT

In this code block variable test should be Promise<number[]> right?

Alas no, it is Promise<number> and I will try to explain why I think that is logical, any suggestions to why it is not is greatly appreciated!

Typing

What our interface tells us is that if we have can deconstruct a key called multiple and its value is true the type should be set to T[] instead of T.

This is the first warning sign for me. To determine the type at what seems to be runtime would certainly cause some issues for at least my simpleton brain. In this case it confused me into thinking that we can rely on checking the multiple key and if it was true we would be in the clear. But when is the multiple key true?

Const (?)

I am not all to familiar with const in javascript and typescript so I will make assumptions and what I write should be mixed with reading the mdn documentation.

Until the very end of my troubleshooting of this code snippet I was in denial regarding const and objects in javascript, I thought in my folly that they were read only. But const does not work like that, the variable opt is readonly but its content can be overwritten with for example opt.multiple = false. This is where I think the problem occurs, the typescript compiler cannot for certainty say that multiple is true and therefore defaults to T instead of T[].

This is somewhat proved with the latter two uses of openPicker(...) where we set multiple to true directly in the function call, leaving nothing to chance when it comes to its value. It is in no way mutable, seen by the first being Promise<number[]> and the second Promise<number> due to when we spread opt.

Conclusion

Me and my friends did not come with any concrete conclusion except that this seemed like the reasonable reason to why the return value was not Promise<number[]> when we sent a const object with multiple set to true. My personal conclusion is that a dynamic way of typing things is really cool, but using a ternary using values that are deconstructed from objects that we cannot say with 100% certainty will be immutable is not implemented correctly or not in the scope of ternary typing.

Thanks to Kenth Ljung and Jonathan borg for the help in debugging and valueable insights regarding. (Kenth was the one who reminded me that objects content is not immutable :) )

[email protected]
© 2020-2022
André Åström [kjof]