Open In App

TypeScript Parameter Type Annotations

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:

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).

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.

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.

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

Article Tags :