0
0
Typescriptprogramming~5 mins

Explicit type annotations in Typescript

Choose your learning style9 modes available
Introduction

Explicit type annotations help you tell the computer exactly what kind of data you expect. This makes your code clearer and helps catch mistakes early.

When you want to make your code easier to understand for others or yourself later.
When you want to avoid mistakes by making sure variables only hold the right kind of data.
When you are working on a big project with many people and want to keep things clear.
When TypeScript cannot guess the type correctly and you want to be sure.
When you want to explain the purpose of a variable or function clearly.
Syntax
Typescript
let variableName: type = value;

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

You can use explicit types for variables, function parameters, and return values.

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 function takes a string called name and returns nothing (void).
Typescript
function greet(name: string): void {
  console.log(`Hello, ${name}!`);
}
This means isActive can only be true or false.
Typescript
let isActive: boolean = true;
Sample Program

This program defines a function multiply that takes two numbers and returns their product. We use explicit type annotations for the parameters and the return type. Then we call the function and print the result.

Typescript
function multiply(x: number, y: number): number {
  return x * y;
}

let result: number = multiply(4, 5);
console.log(`The result is ${result}`);
OutputSuccess
Important Notes

Explicit types make your code safer and easier to read.

TypeScript can often guess types, but adding explicit types helps prevent errors.

You can use explicit types for arrays, objects, and more complex data too.

Summary

Explicit type annotations tell TypeScript exactly what type a variable or function uses.

They help catch mistakes and make code easier to understand.

Use them when you want clear, safe, and readable code.