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.
JavaScript
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.
JavaScript
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.
JavaScript
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.
JavaScript
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.
Similar Reads
TypeScript void Function Void functions in TypeScript are functions that do not return a value. They perform actions or computations without producing a result that needs to be captured. Commonly used for side effects like logging, modifying external state, or triggering asynchronous operations, they enhance code clarity.Sy
3 min read
TypeScript Functions Type TypeScript function types define the structure of a function, including its parameter types and return type, ensuring consistent and type-safe usage.Help validate the types of parameters passed to a function.Ensure the function returns the expected type.Improve code clarity and prevent runtime error
6 min read
TypeScript unknown Function In TypeScript, the unknown type is used for variables whose types aren't known in advance. It ensures type safety by requiring explicit type checks or assertions before usage, preventing arbitrary operations, and promoting safer handling compared to the `any` type.Syntaxfunction gfg(input: unknown):
3 min read
TypeScript Generic Functions TypeScript generic functions allow you to create functions that work with various types while maintaining type safety. By using type parameters, defined within angle brackets (<T>), generics enable functions to operate on different data types without losing the benefits of TypeScript's type-ch
3 min read
TypeScript Function Overloads TypeScript function overloads enable defining multiple signatures for a single function, allowing it to handle various parameter types or counts.Enhances type safety by ensuring correct argument handling.Improves code flexibility and readability.JavaScriptfunction greet(person: string): string; func
3 min read
TypeScript Constraints TypeScript constraints are used in generic type declarations to restrict the types that can be used as type arguments for the generic. Constraints allow you to specify that a generic type parameter must meet certain criteria, such as implementing a particular interface, having a specific method, or
2 min read
PHP gettype() Function The PHP gettype() function returns the type of a variable as a string. It identifies the variable's data type, such as string, integer, array, boolean, etc., allowing developers to check and handle different data types dynamically.Syntax:string gettype ( $var )Parameter: This function accepts a sing
2 min read
TypeScript Anonymous Functions Type In TypeScript, an Anonymous Function Type defines a function without a specific name, specifying parameters and return types. This allows for flexible and reusable function definitions, enabling the assignment of functions to variables and the use of type annotations for parameters and return values
3 min read
Swift - Nested Function A function is a collection of statements grouped together as a block to perform a specific task. The return type of a function decides the type of value returned by the function. For example, if we want to get an integer value from a function then the return type of the function must be Int, if we w
5 min read
TypeScript Function Type Expressions In this article, we are going to learn about TypeScript Function Type Expressions in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, a function type expression represents the type of a function, including its parameter types
3 min read