TypeScript Function
TypeScript functions are blocks of reusable code designed to perform specific tasks. They support object-oriented programming principles like classes and polymorphism. Functions can include type annotations for parameters and return values, enhancing code clarity, safety, and maintainability.
Syntax
function functionName(arg: argType) {
//function Body
}
Where:
- functionName: It is the name of the function
- arg: Argument Name
- argType: Type of the argument
TypeScript Function Types
Parameter type annotations
Parameter type annotations in TypeScript specify the type of each function parameter, ensuring the function receives arguments of the correct type.
Example: In this example we defines a greet function that takes a name parameter of type string and logs a greeting message.
function greet(name: string): void {
console.log(`Hello, ${name}`);
}
greet("Alice");
Output:
Hello, Alice
Return type annotations
We can write the return type of the function post parameter list. This is called Return type annotation.
Example: In this example we defines an add function that takes two number parameters and returns their sum.
function add(a: number, b: number): number {
return a + b;
}
console.log(add(2, 3));
Output:
5
Functions Which Return Promises
Functions that return promises in TypeScript specify Promise<Type> as the return type, indicating asynchronous operations that return a value of the specified type.
Example: In this example we defines an async function greet that returns a Promise with a string.
async function greet(): Promise<string> {
return ("Hello, GeeksforGeeks!!");
}
greet().then(
(result) => {
console.log(result)
}
)
Output:
Hello, GeeksforGeeks!!
Anonymous Function
An anonymous function is a nameless function defined at runtime and stored in a variable. It accepts inputs, returns outputs, and can be called using the variable's name.
Example: In this example we defines an anonymous function to calculate the square of a number and assigns it to the variable square.
const square = function(num: number): number {
return num * num;
};
console.log(square(4));
Output:
16
Conclusion
In this article, we explored various types of TypeScript functions, including parameter type annotations, return type annotations, functions returning promises, and anonymous functions. These features enhance code clarity, safety, reusability, and maintainability, making it easier to write and manage TypeScript code.