Using typeof
with arrays
If you use typeof
with an array value, the result will be "object"
. If you are trying to detect an array value, use Array.isArray
instead.
This is because arrays are internally represented as specialized objects - mappings of arbitrary keys to values - which can lead to some surprising behavior if you are not properly checking array indexes.
As you can see, the indexes of an array are internally represented as strings, so array[10]
is equivalent to array["10"]
.
If TypeScript knows that a value is an array (even any[]
), it will prevent you from using non-numeric keys. It is not recommended to override this behavior by setting the index type to any
- in virtually all cases, it is better to use parseInt
and validate the index before using it.
The unpredictable behavior of JavaScript arrays is one of the major benefits of incorporating TypeScript error checking.
Extracting types from data
There was quite a bit of early emphasis on the difference between types and data. However, there are certain ways in which you can extract a type from the data contained in your program.
If you have an array with values that do not change, you can label the array with as const
and then use typeof
to extract a type union of its values.