Learning how to create an array and set type to Array is very important when you learn Typescript. And how to declare an array of numbers in TypeScript? Let’s go into detail now.
Declare an array of numbers in TypeScript
const anArray = ;
anArray will be set to any type, which any type can pass into an array like an element. Sometimes it will be very helpful, but most of the time, it will lead to errors and misunderstandings when you read your code.
const anArray = [1, "1", 2, 3]; console.log(anArray);
[1, "1", 2, 3]
Here I create a new array but pass in a string ‘1’, and it is wrong when I want to create a number array. So TypeScript provides us with some way if you want to declare only a number array.
Use colon symbol
There are two ways to declare array type after the colon: type  and Array <type>.
const anArray: number = [1, 2, 3, 4, 5]; const anArray1: number = new Array(1, 2, 3, 4, 5); const anArray2: number = Array(1, 2, 3, 4, 6); const anArray3: Array<number> = [1, 2, 3, 4, 5]; const anArray4: Array<number> = new Array(1, 2, 3, 4, 5, 6); const anArray5: Array<number> = Array(1, 2, 3, 4, 5);
Use as keyword
The “as” keyword will help you declare the variable type. So we can create an array with type is any first, then set type as a number array.
const anArray1 =  as number; const anArray2 = new Array() as number; const anArray3 = Array() as number;
There are some more ways to create a number array.
const anArray1 = new Array<number>(); const anArray2 = Array<number>();
After declaring a number array, you can add some elements by the push method.
const anArray: number = ; anArray.push(1); // Add one element anArray.push(2, 3, 4, 5, 6, 7, 8, 9, 10); // Add multiple element console.log(anArray);
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
If we pass in not a number type will lead to the error.
const anArray: number = ; anArray.push("1");
Argument of type 'string' is not assignable to parameter of type 'number'.
Here TypeScript will check for you, and you will never have to worry about type errors. That is what we love in TypeScript.
In this tutorial, I show you how to declare an array of numbers in TypeScript. You can choose the one that you like and feel comfortable with. If you have any problems, please comment below. I will answer as possible. Thanks for reading!
Maybe you are interested:
- Remove element(s) from an array in typescript
- Declare an Empty Array for a typed Variable in TypeScript
- Declare an Array with Fixed length in TypeScript
Name of the university: HOU