JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstypescript
Prev

Learn the concept

Function Types

typescript
junior
functions

How do you type functions in TypeScript?

functions
parameters
return-types
callbacks
rest-parameters
Quick Answer

Functions can be typed by annotating parameters and return type. TypeScript infers return types when possible. Use function type expressions for callbacks, optional/default parameters for flexibility, and overloads for multiple signatures.

Detailed Explanation

Basic Function Typing:

  • Parameter types: (param: type)
  • Return type: function(): returnType
  • TypeScript infers return type if not specified

Function Type Expressions:

  • Type aliases for callback signatures
  • Arrow function syntax: (params) => returnType

Special Cases:

  • Optional parameters: param?: type
  • Default values: param: type = default
  • Rest parameters: ...args: type[]
  • void for no return value
  • never for functions that don't return

Code Examples

Basic function typingTypeScript
// Parameter and return type annotations
function add(a: number, b: number): number {
  return a + b;
}

// Return type inference (can omit if obvious)
function multiply(a: number, b: number) {
  return a * b;  // TypeScript infers number
}

// Arrow function typing
const subtract = (a: number, b: number): number => a - b;

// Function with object parameter
function greet(person: { name: string; age: number }): string {
  return `Hello ${person.name}, you are ${person.age}`;
}

// Using interface for parameters
interface User {
  name: string;
  email: string;
}

function sendEmail(user: User, message: string): void {
  console.log(`Sending to ${user.email}: ${message}`);
}

Real-World Applications

Use Cases

Middleware Pipeline Typing

Typing Express/Hono middleware chains with proper request/response generics

Event Handler Registration

Creating type-safe event systems where handler signatures match event payload types

Higher-Order Component Types

Typing React HOCs and render props with proper generic forwarding

Mini Projects

Type-Safe Event Emitter

intermediate

Build an EventEmitter where emit() enforces correct payload types per event name

Pipe Function

intermediate

Implement a pipe() utility that chains functions with type-safe input/output inference

Industry Examples

Hono

Uses extensively typed middleware and handler functions for type-safe HTTP routing

Ramda

Provides TypeScript definitions for highly generic function composition

Resources

TypeScript - More on Functions

docs

Related Questions

What are generics in TypeScript and how do you use them?

mid
generics
Previous
What are union and intersection types in TypeScript?
Prev