JS Guide
HomeQuestionsSearchResources
Search

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstypescript
Prev
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 typing
// 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}`);
}

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?