0
0
Typescriptprogramming~3 mins

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

Choose your learning style9 modes available
The Big Idea

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

The Scenario

Imagine you are writing a function that adds two numbers, but you forget to check what kind of values are passed in. Sometimes you get strings, sometimes numbers, and sometimes even undefined. This causes your program to behave strangely or crash.

The Problem

Without clear information about what types your function expects, you spend a lot of time debugging unexpected errors. You might accidentally add a number to a string, or call a function with wrong data. This makes your code fragile and hard to maintain.

The Solution

Type annotation on function parameters lets you clearly say what kind of data your function expects. This helps catch mistakes early, before running the code. It also makes your code easier to understand and safer to use.

Before vs After
Before
function add(a, b) {
  return a + b;
}
After
function add(a: number, b: number): number {
  return a + b;
}
What It Enables

It enables you to write functions that are reliable and easy to understand, reducing bugs and improving collaboration.

Real Life Example

When building a calculator app, type annotations ensure that only numbers are added, preventing errors like adding text or missing inputs.

Key Takeaways

Type annotations clarify what data a function expects.

They help catch errors before running the program.

This leads to safer and more maintainable code.