Function types in TypeScript provide a way to describe the shape of functions, including their parameter types and return type. This powerful feature enhances code readability and helps catch errors early in development.
In TypeScript, you can define function types using a syntax similar to arrow functions. Here's a basic example:
type GreetFunction = (name: string) => string;
This defines a function type that takes a string parameter and returns a string.
Once defined, function types can be used to declare variables, function parameters, or return types. For instance:
let greet: GreetFunction;
greet = (name: string) => `Hello, ${name}!`;
console.log(greet("Alice")); // Output: Hello, Alice!
Function types can describe functions with multiple parameters:
type MathOperation = (a: number, b: number) => number;
const add: MathOperation = (a, b) => a + b;
const subtract: MathOperation = (a, b) => a - b;
You can define optional parameters in function types using the ?
symbol:
type LogFunction = (message: string, level?: string) => void;
const log: LogFunction = (message, level = "info") => {
console.log(`[${level.toUpperCase()}]: ${message}`);
};
While function types are concise, interfaces can also describe function shapes and offer more flexibility for future extensions:
interface GreetFunction {
(name: string): string;
defaultName?: string;
}
const greet: GreetFunction = (name) => `Hello, ${name}!`;
greet.defaultName = "Guest";
This approach allows you to add properties to the function object, which isn't possible with simple function types.
Function types in TypeScript provide a robust way to define and work with function shapes. They enhance type safety and code clarity, making them an essential tool for TypeScript developers. By mastering function types, you'll be better equipped to create maintainable and error-resistant code.
For more advanced function-related concepts, explore Function Overloading and Optional and Default Parameters in TypeScript.