I was not sure why pushing the numbers of my range to an array would cause this issue, but quickly learned more as I dove into the intricacies of TypeScript.
Pushing to an Alway Empty Array
The code I was having issues with is the following:
Here I have written a range generation function in TypeScript that should accept two number arguments, the start and end values of the range, and output an array of every number between them, inclusively.
However, after I created my rangeContainer array and began to iterate over the range, I got error highlighting in the push method. This is the error I got:
Argument of type ‘number’ is not assignable to parameter of type ‘never’.
This error shows that I’m trying to push the value of “i”, a number, into my array which has a value of never, but what is never? Never is a newer TypeScript type which is used to specify types that will never occur. This is different from the void type as void can have a null or undefined value. The never type will never have any type assigned to it.
Why was I getting a never type for my array? It was because of how I assigned it. Because I did not specify that my rangeContainer will be an array of numbers, TypeScript assumes that I am creating an empty array that will always be empty. Therefore when I try to add numbers to it on every iteration of the range, it will fail as the number type is not a never type.
There are ways to solve this by simply dropping out the type declaration of the rangeContainer, but we want to use Typescript to its fullest. Therefore we can specify the array value types to clarify that we don’t want an empty array:
Now we have correctly declared a non-empty array that has number type values instead of the never type. Our range can be built without any shortcuts to bypass TypeScript so we can feel great about what we are writing!
TypeScript can be a pain at times, but this is really a challenge to us as developers to truly understand what we are coding. I hope that you have learned more about list type declarations as well as the less common never type. Leave a comment below of your biggest TypeScript gotcha you have run into!