0
0
Typescriptprogramming~3 mins

Why Type annotation on variables in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your code could warn you about mistakes before you even run it?

The Scenario

Imagine you are writing a program where you store numbers, words, or true/false values in variables without telling anyone what type they are. Later, when you try to use these variables, you might get confused or make mistakes because you don't know what kind of data they hold.

The Problem

Without clear type information, your program can break unexpectedly. You might add a number to a word by mistake or call a function on something that doesn't support it. Finding these errors by testing alone can be slow and frustrating.

The Solution

Type annotation lets you tell the program exactly what kind of data each variable should hold. This helps catch mistakes early, makes your code easier to understand, and guides you while writing it.

Before vs After
Before
let age;
age = 25;
age = 'twenty-five'; // Oops, no error here
After
let age: number;
age = 25;
age = 'twenty-five'; // Error: Type 'string' is not assignable to type 'number'
What It Enables

It makes your code safer and clearer, so you can build bigger programs with confidence.

Real Life Example

Think of filling out a form where you must enter your age as a number. If someone types letters instead, the form warns them immediately. Type annotation works like that warning in your code.

Key Takeaways

Type annotation tells what kind of data a variable holds.

It helps catch mistakes before running the program.

It makes code easier to read and maintain.