Open In App

How to Declare Variables with Explicit Types in TypeScript ?

Last Updated : 24 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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"

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads