Type annotations help you tell the computer what kind of information a function expects. This makes your code safer and easier to understand.
0
0
Type annotation on function parameters in Typescript
Introduction
When you want to make sure a function only gets numbers as input.
When you want to explain what type of data a function should receive to your team.
When you want to catch mistakes early by checking input types before running the program.
When you want your code editor to give helpful suggestions while you write functions.
When you want to avoid bugs caused by wrong data types being passed to functions.
Syntax
Typescript
function functionName(parameterName: type) { // function body }
The colon : after the parameter name is used to add the type.
You can use many types like string, number, boolean, or even custom types.
Examples
This function expects a
string called name. It prints a greeting.Typescript
function greet(name: string) { console.log(`Hello, ${name}!`); }
This function expects a
number called num and returns its square.Typescript
function square(num: number) { return num * num; }
This function expects a
number and returns a boolean telling if the age is 18 or more.Typescript
function isAdult(age: number): boolean { return age >= 18; }
Sample Program
This program defines a function that multiplies two numbers. It uses type annotations to make sure both inputs are numbers and the output is also a number. Then it calls the function and prints the result.
Typescript
function multiply(a: number, b: number): number { return a * b; } const result = multiply(4, 5); console.log(`4 times 5 is ${result}`);
OutputSuccess
Important Notes
If you pass the wrong type, TypeScript will show an error before running the code.
Type annotations do not change how the program runs; they help you catch mistakes early.
You can add types to return values too, after the parentheses.
Summary
Type annotations tell what kind of data a function expects.
They help catch errors and make code easier to read.
Use a colon : after the parameter name to add a type.