0
0
Typescriptprogramming~5 mins

Type annotation on variables in Typescript

Choose your learning style9 modes available
Introduction

Type annotation helps you tell the computer what kind of value a variable will hold. This makes your code safer and easier to understand.

When you want to make sure a variable only holds numbers.
When you want to explain to others what type of data a variable should have.
When you want to catch mistakes early if you try to put the wrong type of value in a variable.
When you want your code editor to give you helpful hints and warnings.
When you are working on bigger projects with many people and want clear rules for data.
Syntax
Typescript
let variableName: type = value;

The colon : is used to add the type after the variable name.

You can use many types like number, string, boolean, or even custom types.

Examples
This means age can only hold numbers.
Typescript
let age: number = 25;
This means name can only hold text (strings).
Typescript
let name: string = "Alice";
This means isStudent can only be true or false.
Typescript
let isStudent: boolean = true;
You can declare a variable with a type but assign a value later.
Typescript
let score: number;
Sample Program

This program shows how to use type annotations for different variables and prints their values.

Typescript
let height: number = 180;
let firstName: string = "John";
let isActive: boolean = false;

console.log(`Name: ${firstName}`);
console.log(`Height: ${height} cm`);
console.log(`Active user: ${isActive}`);
OutputSuccess
Important Notes

If you try to assign a value of the wrong type, TypeScript will show an error before running your code.

Type annotations are optional if TypeScript can guess the type from the value, but adding them helps clarity.

Summary

Type annotations tell what kind of value a variable can hold.

They help catch mistakes early and make code easier to read.

Use a colon : after the variable name to add a type.