TypeScript Functions: How to Type Functions the Right Way
Sep 2,2026

Series: TypeScript from Basics to Advanced
Part: 3 — TypeScript Functions
Level: Beginner → Intermediate


Introduction

Functions are one of the most important building blocks of JavaScript applications.

In JavaScript, we can write a function without specifying what type of data it expects:

function add(a, b) {
  return a + b;
}

This is perfectly valid JavaScript.

But what happens if someone calls:

add(10, "20");

JavaScript allows it.

The result is:

"1020"

In a small application, this might be easy to catch. In a large application, however, functions can be called from dozens or even hundreds of places.

This is where TypeScript becomes useful.

With TypeScript, we can define exactly what a function expects and what it returns:

function add(a: number, b: number): number {
  return a + b;
}

Now TypeScript can catch incorrect usage before the application runs.

In this article, we'll learn how to properly type functions in TypeScript.


1. Function Parameters

Let's start with a simple function.

function greet(name: string) {
  console.log(`Hello ${name}`);
}

Here:

name: string

means that the name parameter must be a string.

This is valid:

greet("Sundar");

But this produces a TypeScript error:

greet(100);

because 100 is a number.

Multiple Parameters

You can specify a type for every parameter:

function calculateTotal(price: number, quantity: number) {
  return price * quantity;
}

Now:

calculateTotal(100, 3);

is valid.

But:

calculateTotal("100", 3);

is not valid.


2. Function Return Types

We can also specify what a function should return.

function add(a: number, b: number): number {
  return a + b;
}

The syntax is:

function functionName(parameter: type): returnType

So:

function add(a: number, b: number): number

means:

a       → number
b       → number
return  → number

If we accidentally return a string:

function add(a: number, b: number): number {
  return "Hello";
}

TypeScript reports an error.

This is useful because the function's contract is clear.


3. Return Type Inference

Just like variables, TypeScript can infer function return types.

For example:

function add(a: number, b: number) {
  return a + b;
}

TypeScript understands that the return type is:

number

So you don't always have to explicitly write:

function add(a: number, b: number): number

However, explicit return types can be useful for public functions, APIs, services, and important business logic because they make the intended contract clear.


4. Arrow Functions

TypeScript works naturally with JavaScript arrow functions.

const add = (a: number, b: number): number => {
  return a + b;
};

We can also write:

const multiply = (a: number, b: number): number => a * b;

Here:

a → number
b → number
return → number

Type Inference With Arrow Functions

This is also valid:

const multiply = (a: number, b: number) => a * b;

TypeScript infers the return type as number.


5. Optional Parameters

Sometimes a function parameter isn't required.

TypeScript allows us to mark a parameter as optional using ?.

function greet(name: string, age?: number) {
  console.log(name);
}

Now both are valid:

greet("Sundar");

greet("Sundar", 25);

But:

greet();

is invalid because name is required.

An optional parameter effectively means the value may be undefined.

For example:

function greet(name: string, age?: number) {
  if (age !== undefined) {
    console.log(`Age: ${age}`);
  }
}

6. Optional Parameters Must Come After Required Parameters

This is important.

Correct:

function createUser(
  name: string,
  email?: string
) {}

Incorrect:

function createUser(
  email?: string,
  name: string
) {}

Required parameters cannot normally come after optional parameters.


7. Default Parameters

JavaScript allows default values, and TypeScript supports them.

function greet(
  name: string,
  greeting: string = "Hello"
) {
  console.log(`${greeting} ${name}`);
}

Now:

greet("Sundar");

uses:

Hello Sundar

And:

greet("Sundar", "Welcome");

uses:

Welcome Sundar

A parameter with a default value is effectively optional when calling the function.


8. Rest Parameters

Rest parameters allow a function to accept multiple values.

function sum(...numbers: number[]): number {
  return numbers.reduce((total, number) => {
    return total + number;
  }, 0);
}

Now we can call:

sum(10, 20);

sum(10, 20, 30, 40);

sum(1, 2, 3, 4, 5);

The numbers parameter is typed as:

number[]

This is useful when the number of arguments isn't fixed.


9. Function Types

Sometimes we don't just want to type the parameters of a function.

We want to describe the entire function.

For example:

let add: (a: number, b: number) => number;

This means:

add must be a function that accepts two numbers and returns a number.

We can then assign:

add = (a, b) => a + b;

This is valid.

But this isn't:

add = (a, b) => `${a}${b}`;

because the function returns a string instead of a number.


10. Function Type Alias

If you use the same function type in multiple places, you can create a type alias.

type Calculator = (
  a: number,
  b: number
) => number;

Now:

const add: Calculator = (a, b) => a + b;

const multiply: Calculator = (a, b) => a * b;

This makes reusable function contracts possible.


11. Callback Functions

One of the most important uses of function types is typing callbacks.

Consider this function:

function calculate(
  a: number,
  b: number,
  operation: (x: number, y: number) => number
): number {
  return operation(a, b);
}

The operation parameter is itself a function.

It must:

accept → two numbers
return → a number

Now we can pass different functions:

const add = (a: number, b: number) => a + b;

const multiply = (a: number, b: number) => a * b;

Then:

calculate(10, 20, add);

calculate(10, 20, multiply);

This pattern appears everywhere in JavaScript and TypeScript.

For example:

[1, 2, 3].map(number => number * 2);

The function passed to map() is a callback.


12. Typing Callbacks in Real Applications

Suppose we have a list of users:

interface User {
  id: number;
  name: string;
}

We could create a function that accepts a callback:

function processUser(
  user: User,
  callback: (user: User) => void
): void {
  callback(user);
}

Usage:

processUser(
  {
    id: 1,
    name: "Sundar"
  },
  (user) => {
    console.log(user.name);
  }
);

TypeScript knows that user is a User.

This is one of the reasons TypeScript provides such good autocomplete.


13. Functions Returning void

A function that doesn't return a meaningful value can use void.

function logMessage(message: string): void {
  console.log(message);
}

The function performs an action but doesn't return a value.

Another example:

function sendNotification(message: string): void {
  console.log(`Notification: ${message}`);
}

void is particularly common when defining callback functions:

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

14. void Does Not Mean "Nothing Can Happen"

This is a subtle but important point.

Consider:

function logMessage(): void {
  console.log("Hello");
}

The function absolutely does something.

void means that the caller shouldn't expect a useful return value.

It does not mean that the function does nothing.


15. Functions Returning never

We learned about never in the previous article.

A function can return never when it never successfully returns.

For example:

function throwError(message: string): never {
  throw new Error(message);
}

The function always throws an error.

Another example:

function infiniteLoop(): never {
  while (true) {
    // Runs forever
  }
}

The important distinction is:

void
 ↓
Function finishes without returning a useful value

never
 ↓
Function never successfully finishes

16. Async Functions

TypeScript also provides excellent support for asynchronous functions.

Consider:

async function getUser() {
  const response = await fetch("/api/user");

  return response.json();
}

An async function always returns a Promise.

We can explicitly specify the resolved value:

interface User {
  id: number;
  name: string;
}

async function getUser(): Promise<User> {
  const response = await fetch("/api/user");

  return response.json();
}

Now TypeScript understands:

getUser()
     ↓
Promise<User>

This is extremely useful when working with APIs.


17. Promise Return Types

Suppose an API returns multiple users:

async function getUsers(): Promise<User[]> {
  const response = await fetch("/api/users");

  return response.json();
}

The return type is:

Promise<User[]>

Not:

User[]

because the function is asynchronous.

This distinction is important when working with:

  • fetch

  • Axios

  • React Query

  • Node.js APIs

  • Database queries


18. Function Overloads

TypeScript also supports function overloads.

Suppose a function can accept either a string or a number and return a corresponding value.

We can define overload signatures:

function format(value: string): string;
function format(value: number): string;

function format(value: string | number): string {
  return String(value);
}

Now TypeScript understands both valid calls:

format("Hello");

format(100);

Function overloads become useful when a function has multiple well-defined calling patterns.

We'll explore overloads more deeply when we move into advanced TypeScript.


19. Generic Functions

One of the most powerful features of TypeScript is generics.

Consider:

function identity(value: any) {
  return value;
}

Although this works, any removes useful type information.

Instead, we can use a generic:

function identity<T>(value: T): T {
  return value;
}

Now:

const name = identity("Sundar");

TypeScript understands:

name → string

And:

const age = identity(25);

TypeScript understands:

age → number

The same function works with different types while preserving type information.

Generics are one of the most important topics we'll cover later in this series.


20. Function Type vs Function Implementation

It's useful to understand the difference between these two:

type AddFunction = (
  a: number,
  b: number
) => number;

This describes the shape of a function.

And:

const add: AddFunction = (a, b) => {
  return a + b;
};

This is the actual implementation.

Think of it as:

Function type
      ↓
Defines the contract
      ↓
Function implementation
      ↓
Provides the behavior

21. A Real-World Example

Let's combine what we've learned.

Suppose we're creating a user service.

interface User {
  id: number;
  name: string;
  email: string;
}

We can define a function:

function getUserName(user: User): string {
  return user.name;
}

Now an asynchronous API function:

async function getUser(
  id: number
): Promise<User> {
  const response = await fetch(`/api/users/${id}`);

  return response.json();
}

And a callback:

function processUser(
  user: User,
  callback: (user: User) => void
): void {
  callback(user);
}

This gives us a strongly typed flow:

User
 ↓
getUser()
 ↓
Promise<User>
 ↓
processUser()
 ↓
callback(User)

This is much closer to how TypeScript is used in real applications.


22. Common Mistakes

Mistake 1: Using any for Function Parameters

Avoid:

function calculate(a: any, b: any) {
  return a + b;
}

Prefer:

function calculate(a: number, b: number): number {
  return a + b;
}

Mistake 2: Forgetting Callback Types

Avoid:

function processUser(user: User, callback: any) {
  callback(user);
}

Prefer:

function processUser(
  user: User,
  callback: (user: User) => void
) {
  callback(user);
}

Mistake 3: Using User[] Instead of Promise<User[]>

For an async function:

async function getUsers(): Promise<User[]> {
  // ...
}

not:

async function getUsers(): User[] {
  // ...
}

An async function returns a Promise.


Mistake 4: Over-annotating Obvious Return Types

This isn't wrong:

const add = (
  a: number,
  b: number
): number => {
  return a + b;
};

But TypeScript can infer the return type:

const add = (a: number, b: number) => {
  return a + b;
};

Don't add annotations simply because you can.

Use them when they improve clarity or define an important contract.


Best Practices

1. Type function parameters

function greet(name: string) {}

2. Let TypeScript infer obvious return types

function add(a: number, b: number) {
  return a + b;
}

3. Explicitly type important API/service boundaries

async function getUser(): Promise<User> {
  // ...
}

4. Avoid any

// Avoid
callback: any

// Prefer
callback: (user: User) => void

5. Use function types for reusable contracts

type Calculator = (
  a: number,
  b: number
) => number;

6. Use generics when you need reusable type-safe functions

function identity<T>(value: T): T {
  return value;
}

Final Takeaway

Functions are where TypeScript starts becoming extremely practical.

The most important concepts from this article are:

Parameters
     ↓
Return types
     ↓
Optional parameters
     ↓
Default parameters
     ↓
Rest parameters
     ↓
Function types
     ↓
Callbacks
     ↓
void / never
     ↓
Async functions
     ↓
Generics

If you understand these concepts, you'll already be able to write strongly typed functions for many real-world applications.

The key principle is:

A function's type describes its contract: what it accepts and what it returns.

For example:

function add(a: number, b: number): number {
  return a + b;
}

This tells other developers—and TypeScript—exactly how the function should be used.