To add a number type annotation to a variable or a constant, you can declare the variable or constant followed by a
: (colon) symbol and then the type
number in TypeScript.
For example, let's say we have a variable called
myNumber and want to only have the
number type as the values. To do that we can annotate the type
number to the
myNumber variable like this,
// add number type to a variable let myNumber: number;
After initialization, let's assign a number value of
100 to the variable
myNumber. It can be done like this,
// add number type to a variable let myNumber: number; // assign a number value to the myNumber variable myNumber = 100; // ✅ allowed
As you can see from the above code TypeScript allowed us to assign the number value of
100 to the variable
myNumber since the allowed type for the
myNumber variable is
Now let's try to assign another value of
Hello World! to the
myNumber variable to see what happens,
// add number type to a variable let myNumber: number; // assign a number value to the myNumber variable myNumber = 100; // ✅ allowed // assign a value of type other than a number myNumber = "Hello World!"; // ❌ not allowed. Type 'string' is not assignable to type 'number'.
As you can see that the TypeScript will throw an error saying that the
Type 'string' is not assignable to type 'number'. which is also what we want to happen.
Most of the time TypeScript will try to infer the type of the variable from the value it is assigned.
For example, let's declare a variable called
myFavNum and assign the
number value of '1000' without actually declaring the type
number as we did above. It can be done like this,
// Typescript infers the type from // the value it is assigned let myFavNum = 1000;
Now if you hover over the variable
myFavNum we can see that TypeScript has automatically got that type of the variable
myFavNum is of type
Since the TypeScript has already got the type is of
number value and whenever we try to reassign a value other than the type
number, The compiler will throw errors like from the above.
See the execution of the above codes live in codesandbox.
That's all 😃!