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}!`;
}
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}`;
}
You can assign default values to parameters:
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}`;
}
Rest parameters allow a function to accept an indefinite number of arguments as an array:
function joinNames(...names: string[]): string {
return names.join(", ");
}
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.`;
}
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);
}
TypeScript supports arrow functions, which are a more concise way of writing functions:
const add = (x: number, y: number): number => x + y;
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}`);
}
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
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.