Aliasing Function Types
You'll learn how to create reusable type aliases for function signatures, making callback types cleaner and more maintainable.
When you're working with functions that accept callbacks or return functions, writing the full function type every time gets messy. Type aliases solve this by letting you name a function signature once and reuse it everywhere.
The Core Idea
Just like you can alias an object type, you can alias a function type. This is especially useful when you have callbacks, event handlers, or functions that share the same signature across your codebase.
Think of it like creating a template for what a function should look like. Instead of describing "a function that takes a number and returns a string" every single time, you create a NumberFormatter type once and use that name instead.
Basic Syntax
Here's how you create a function type alias:
type Handler = (req: Request) => Response;
This creates a reusable type called Handler that describes any function accepting a Request and returning a Response.
You can then use it wherever you need that function shape:
function processRequest(handler: Handler) {
// handler must match the Handler signature
}
const myHandler: Handler = (req) => {
// TypeScript knows req is a Request
return someResponse;
};
The beauty here is that parameter names in the alias (req) are just for documentation—when you implement the function, TypeScript still enforces the types but lets you rename parameters as needed.
Key Takeaway: Type aliases can describe function signatures like type Handler = (req: Request) => Response, giving you a reusable name for callback and function types that makes your code more readable and maintainable.