To add a number array
type annotation to a variable or a constant, you can declare the variable name followed by a :
(colon) symbol, then the number
type with []
(opening and closing square brackets) symbol.
For example, let's say we have a variable called nums
and want to only have the number
type as the values in the array. To do that we can annotate the number
array type to the nums
variable like this,
// add number array type to a variable
let nums: number[];
After initialization, let's add a number value of 100
to the nums
array. It can be done like this,
// add number array type to a variable
let nums: number[];
// add a number value to the nums array
nums = [100]; // ✅ allowed
As you can see from the above code TypeScript allowed us to add the number value of 100
to the number type array nums
since the allowed type for the nums
array is a number
type.
Now let's try to add another value of string
type Hello World!
to the nums
array to see what happens,
// add number array type to a variable
let nums: number[];
// add a number value to the nums array
nums = [100]; // ✅ allowed
// add a value of type other than number
nums = [100, "Hello World!"]; // ❌ not allowed. Type 'string' is not assignable to type 'number'.
You can see that TypeScript will throw an error saying 'Type 'string' is not assignable to type 'number'
, which is also what we want.
Also, we cannot use the push()
method to add a value other than the number
type.
Bonus
When a variable is assigned a value, TypeScript will attempt to determine the type of the variable.
For example, let's declare a variable called favNums
and add number
values like 10
, 20
, 30
without actually declaring the number array type annotation as we did above. It can be done like this,
// Typescript infers the type from
// the value it is assigned
let favNums = [10, 20, 30];
As you can see when you hover over the variable favNums
, TypeScript has automatically detected that the variable favNums
is a number
array type.
Since the TypeScript has already got the type is of number
array type and whenever we try to reassign a value other than the number
array type, The compiler will throw errors like from the above.
See the execution of the above codes live in codesandbox.
That's all 😃!