Back

TypeScript Function Type

In TypeScript, a function type is used to define the types of a function’s parameters and its return value. This improves both the readability and safety of your code.

How to Define a Function Type?

let greet: (name: string) => string;
greet = (name) => `Hello, ${name}!`;

The `greet` variable only accepts functions that take a string parameter and return a string. If a function with an incorrect type is assigned, TypeScript will throw an error.

Multiple Parameters and Return Values

let calculate: (a: number, b: number, op: string) => number;
calculate = (a, b, op) => {
  return op === "add" ? a + b : a - b;
};

With function types, you can explicitly define the structure of functions that take multiple parameters. This makes incorrect usage easier to detect.

Using Type Alias for Function Types

type Logger = (message: string) => void;

const log: Logger = (msg) => {
  console.log("[LOG]:", msg);
};

You can define reusable function types using `type` aliases. This is especially useful for callback functions.

Passing a Function as a Parameter

function handleClick(callback: () => void) {
  callback();
}

You can pass a function as a parameter to another function. This pattern is commonly used in scenarios like event handlers and async operations.

Optional and Default Parameters

function sendEmail(to: string, subject: string = "No Subject", body?: string): void {
  console.log(`To: ${to}, Subject: ${subject}, Body: ${body ?? "Empty"}`);
}

Function parameters can be marked as optional using `?` or assigned default values. This helps you build more flexible APIs.

Type Safety Advantage with Function Types

Using function types helps you catch issues like passing incorrect parameters or returning the wrong type before runtime. This leads to more stable and maintainable applications.

Back