0
0
Typescriptprogramming~5 mins

Parameter type annotations in Typescript

Choose your learning style9 modes available
Introduction

Parameter type annotations help you tell the computer what kind of information a function expects. This makes your code clearer and helps catch mistakes early.

When writing a function that takes inputs and you want to be sure those inputs are the right kind.
When working with others and you want to make your code easier to understand.
When you want your code editor to help you by showing errors if you use the wrong input type.
When building bigger programs where keeping track of data types helps avoid bugs.
Syntax
Typescript
function functionName(parameterName: type) {
  // function body
}

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

Common types include string, number, and boolean.

Examples
This function expects a string as the name.
Typescript
function greet(name: string) {
  console.log(`Hello, ${name}!`);
}
This function expects a number and returns its square.
Typescript
function square(num: number) {
  return num * num;
}
This function expects a number and returns a boolean.
Typescript
function isAdult(age: number): boolean {
  return age >= 18;
}
Sample Program

This program defines a function that multiplies two numbers. It uses parameter type annotations to ensure both inputs are numbers. 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

Type annotations do not change how the program runs; they help during coding and checking.

If you pass the wrong type, TypeScript will show an error before running the code.

Summary

Parameter type annotations tell what kind of data a function expects.

They help catch mistakes and make code easier to understand.

Use a colon : after the parameter name followed by the type.