Open In App

How to Declare Variables with Explicit Types in TypeScript ?

In TypeScript, you declare variables with explicit types by specifying the type of the variable after its name using a colon (:) followed by the desired data type which can be string, number, etc.

Example 1: Here, the variable age is explicitly declared with the type number. This means it can only store numerical values, and TypeScript will enforce this type of constraint. If you try to assign a value of a different type to the variable, TypeScript will raise a type error during compilation.

// Declaring a variable with an explicit type
let age: number;

// Assigning a value to the variable
age = 25;

// Now, the variable 'age' can only hold numerical values

Example 2: you can also declare and initialize a variable in a single line.

// Declaring and initializing a variable with an explicit type
let name: string = "John";

// Now, the variable 'name' is of type string and holds the value "John"
Article Tags :