What if your functions could warn you about mistakes before you even run your code?
Why Type annotation on function parameters in Typescript? - Purpose & Use Cases
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.
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.
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.
function add(a, b) {
return a + b;
}function add(a: number, b: number): number {
return a + b;
}It enables you to write functions that are reliable and easy to understand, reducing bugs and improving collaboration.
When building a calculator app, type annotations ensure that only numbers are added, preventing errors like adding text or missing inputs.
Type annotations clarify what data a function expects.
They help catch errors before running the program.
This leads to safer and more maintainable code.