Open In App

TypeScript Parameter Type Annotations

Last Updated : 15 May, 2024
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

Example 3: Generics provide a way to create functions that can work with any data type. In this example, the identity function uses a generic type T. This allows the function to accept any type of argument and return a value of the same type. The function calls demonstrate how identity can be used with different types.

JavaScript
function identity<T>(arg: T): T {
    return arg;
}

console.log(identity<string>("GFG")); // Output: GFG
console.log(identity<number>(22)); // Output: 22

Output:

GFG
22

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