Open In App

TypeScript Parameter Type Annotations

Last Updated : 06 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

TypeScript Parameter type annotations are used to specify the expected data types of function parameters. They provide a way to explicitly define the types of values that a function expects as arguments. Parameter type annotations are part of TypeScript’s static typing system, and they help catch type-related errors during development.

Syntax

function functionName(param1: Type1, param2: Type2, ...): ReturnType {
// Function body
}

Parameters:

  • functionName: This is the name of the function.
  • param1, param2, …: These are the names of the function parameters.
  • Type1, Type2, …: These are the type annotations specifying the expected data types of the parameters.
  • ReturnType: This is the type annotation specifying the expected return type of the function.

Example 1: In this example, greet is a function that takes two parameters: name (of type string) and age (of type number).The type annotations name: string and age: number specify the expected data types for these parameters. The function returns a string (string is the return type annotation).

Javascript




function greet(name: string, age: number): string {
    return `Hello, ${name}! You are ${age} years old.`;
}
  
console.log(greet("GeeksforGeeks", 30));


Output:

z20

Example 2: In this example, We have a function calculateArea that takes two parameters: length and width, both of type number. Inside the function, it calculates the area of a rectangle by multiplying length and width and returns the result as a number. We declare two variables, length and width, and assign numeric values to them. We call the calculateArea function with length and width as arguments and store the result in the area variable.

Finally, we log a message to the console that includes the calculated area.

Javascript




function calculateArea(x: number, y: number): number {
    return x * y;
}
  
const leng = 5;
const wid = 4;
const area = calculateArea(leng, wid);
  
console.log(
    `The area of a rectangle with length 
     ${leng} and width ${wid} is ${area}.`
    );


Output:

z21

Reference: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#parameter-type-annotations



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads