![]() |
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. Syntaxfunction functionName(arg: argType) {
//function Body
} Where:
TypeScript Function TypesParameter type annotationsParameter 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.
Output: Hello, Alice Return type annotationsWe 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.
Output: 5 Functions Which Return PromisesFunctions 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.
Output: Hello, GeeksforGeeks!! Anonymous FunctionAn 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.
Output: 16 ConclusionIn 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. |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |