Mastering TypeScript Function Signatures & Overloads
· TypeScript · By Zeeshan Ahmad
TypeScript Function Signature Syntax with Explanation
Basic Function Signature
In TypeScript, function signatures describe the parameters and return type of a function. Here's a simple example:
function greet(name: string): string {
return `Hello, ${name}!`;
}
Optional Parameters
TypeScript allows you to mark certain parameters as optional by adding a ? after the parameter name:
function greet(name: string, title?: string): string {
if (title) {
return `Hello, ${title} ${name}`;
}
return `Hello, ${name}`;
}
Default Parameters
You can assign default values to parameters:
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}`;
}
Rest Parameters
Rest parameters allow a function to accept an indefinite number of arguments as an array:
function joinNames(...names: string[]): string {
return names.join(", ");
}
Function Signature with Object Types
You can also define functions that accept complex types, such as objects:
interface User {
name: string;
age: number;
}
function greetUser(user: User): string {
return `Hello, ${user.name}. You are ${user.age} years old.`;
}
Return Types: Void, Never, and More
A function that doesn't return anything has a return type of void:
function logMessage(message: string): void {
console.log(message);
}
A function that never returns (usually because it throws an error or goes into an infinite loop) has a return type of never:
function throwError(message: string): never {
throw new Error(message);
}
Arrow Function Syntax
TypeScript supports arrow functions, which are a more concise way of writing functions:
const add = (x: number, y: number): number => x + y;
Function Overloading
TypeScript also supports function overloading, allowing multiple function signatures with different parameter types. The function body must handle the variations:
function call(phoneNumber: string): void;
function call(phoneNumber: number): void;
function call(phoneNumber: any): void {
console.log(`Calling ${phoneNumber}`);
}
Generic Functions
Generics allow functions to work with a variety of types, specified when the function is called:
function identity(arg: T): T {
return arg;
}
const num = identity(42); // num is of type number
const str = identity("Hello"); // str is of type string
Conclusion
TypeScript function signatures are a powerful way to enforce type safety and flexibility in your code. With various features like optional parameters, default values, rest parameters, and generics, you can create robust and flexible functions for a wide range of use cases.