0
0
Typescriptprogramming~5 mins

Type alias for functions in Typescript

Choose your learning style9 modes available
Introduction

A type alias for functions helps you give a simple name to a function's shape. This makes your code easier to read and reuse.

When you want to describe what kind of function you expect as input or output.
When you have many functions with the same parameters and return type.
When you want to make your code clearer by naming function types.
When you want to avoid repeating the same function type everywhere.
When you want to check that functions follow a specific pattern.
Syntax
Typescript
type FunctionName = (param1: Type1, param2: Type2) => ReturnType;
Use type keyword to create a new name for a function type.
The arrow => shows the return type of the function.
Examples
This means Greet is a function type that takes a string and returns nothing.
Typescript
type Greet = (name: string) => void;
Add is a function type that takes two numbers and returns a number.
Typescript
type Add = (a: number, b: number) => number;
Compare is a function type that takes two numbers and returns true or false.
Typescript
type Compare = (x: number, y: number) => boolean;
Sample Program

We create a type alias Multiply for a function that takes two numbers and returns a number. Then we make a function multiply that matches this type. Finally, we print the result of multiplying 4 and 5.

Typescript
type Multiply = (x: number, y: number) => number;

const multiply: Multiply = (x, y) => x * y;

console.log(multiply(4, 5));
OutputSuccess
Important Notes

Type aliases do not create new functions, they just name the shape of functions.

You can use type aliases to make your code easier to understand and maintain.

Summary

Type alias for functions gives a simple name to a function's input and output types.

This helps avoid repeating function type definitions.

It makes your code clearer and easier to check for mistakes.