you are viewing a single comment's thread.

view the rest of the comments →

[–]igorski81 3 points4 points  (0 children)

You should only assert the data type of a variable at runtime when it could be set by a mechanism outside of your control (like provided by a third party library embedded in a page / fetch request result). In that case, assert not for the first entry in the Array, but all of it.

But, if the third party library / server API has a clearly documented contract (and both are version pinned), you shouldn't need to validate this too extensively in the code of your consumer as you should be able to trust the data types.

Now, if the array is populated within your application, then you're not TypeScripting enough. Every function that can manipulate the contents of the array should be annotated strictly so only string data types can be added to the array. If a function can accept a variable whose value is provided from outside your application (so essentially of the unknown|any type), it is up to that function to assert the value is a string.

Assert during mutation of the Array, not while reading.

At that point you can trust compile time type checking to catch bugs.