Skip to content
intermediatePhase 35 · TypeScript

Function Types

Type function parameters, return values, callbacks, and overloads.

30m
0 problems
Topic Progress0%

Function Type Annotations

Function Type Annotations

Basic Function Types

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

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

// Function type
const divide: (a: number, b: number) => number = (a, b) => a / b;

Void Return Type

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

// void means function doesn't return anything
// You can return undefined, but not a value
function noop(): void {
  return undefined; // OK
  // return 42; // Error!
}

Never Return Type

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

function infiniteLoop(): never {
  while (true) {}
}

Function Type Aliases

type Callback = (data: string) => void;
type Predicate<T> = (item: T) => boolean;
type Mapper<T, U> = (item: T) => U;

function process(items: string[], callback: Callback): void {
  items.forEach(callback);
}

const numbers = [1, 2, 3];
const isEven: Predicate<number> = (n) => n % 2 === 0;
const doubled: Mapper<number, string> = (n) => String(n * 2);

Optional Parameters

Optional Parameters

Optional Parameters

Use ? for parameters that can be omitted:

function greet(name: string, greeting?: string): string {
  return `${greeting || "Hello"}, ${name}!`;
}

greet("Alice"); // "Hello, Alice!"
greet("Bob", "Hi"); // "Hi, Bob!"

Default Parameters

function greet(name: string, greeting: string = "Hello"): string {
  return `${greeting}, ${name}!`;
}

greet("Alice"); // "Hello, Alice!"
greet("Bob", "Hi"); // "Hi, Bob!"

Rest Parameters

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

sum(1, 2, 3); // 6
sum(1, 2, 3, 4, 5); // 15

// With other parameters
function log(level: string, ...messages: string[]): void {
  console.log(`[${level}]`, ...messages);
}

log("INFO", "Server started", "on port 3000");

Parameter Ordering

// Required must come before optional
function createUser(
  name: string,      // required
  age: number,       // required
  email?: string     // optional
) {}

// Default can go anywhere (but usually last)
function config(
  host: string = "localhost",
  port: number,
  debug: boolean = false
) {}

config("example.com", 8080); // uses defaults

Function Overloads

Function Overloads

Function overloads allow a function to have multiple signatures.

Basic Overloads

function format(input: string): string;
function format(input: number): string;
function format(input: Date): string;
function format(input: string | number | Date): string {
  if (typeof input === "string") {
    return input.toUpperCase();
  } else if (typeof input === "number") {
    return input.toFixed(2);
  } else {
    return input.toISOString();
  }
}

format("hello"); // "HELLO"
format(3.14159); // "3.14"
format(new Date()); // ISO string

Overloads with Different Returns

function createElement(tag: "div"): HTMLDivElement;
function createElement(tag: "span"): HTMLSpanElement;
function createElement(tag: string): HTMLElement;
function createElement(tag: string): HTMLElement {
  return document.createElement(tag);
}

const div = createElement("div"); // HTMLDivElement
const span = createElement("span"); // HTMLSpanElement

Overloads vs Union Types

// Union type (simpler)
function process(input: string | number): string {
  return String(input);
}

// Overload (more precise)
function process(input: string): string;
function process(input: number): string;
function process(input: string | number): string {
  return String(input);
}

// Overload gives more specific return types
function getLength(input: string): number;
function getLength(input: Array<any>): number;
function getLength(input: string | Array<any>): number {
  return input.length;
}

Practice Problems

0/3solved
Build Function Types Component

Create a reusable React component implementing Function Types. Include proper state management and accessibility.

Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where needed
Function Types Testing

Write unit and integration tests for Function Types using React Testing Library.

Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility tests
Function Types Performance

Optimize Function Types for performance. Consider memoization, code splitting, and bundle size.

Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysis

Quiz

1. What is the return type for a function that doesn't return a value?

Question 1 options

2. How do you make a function parameter optional?

Question 2 options

3. What is the difference between void and never?

Question 3 options

4. When should you use function overloads?

Question 4 options

Flashcards

Question

How do you type a function parameter?

Answer

param: type, e.g., name: string

Question

How do you type a function return value?

Answer

Add : type after parameters, e.g., (): number

Question

What is a rest parameter?

Answer

...args: type[] for variable number of arguments

Question

What are function overloads?

Answer

Multiple signatures for a single function implementation

Question

What is Function Types?

Answer

Function Types is a key concept in frontend development.

Revision Notes

Key Takeaways

  • 1.Use void for functions that don't return values
  • 2.Use never for functions that never return
  • 3.Optional parameters use ? and must come after required
  • 4.Default parameters use = and can go anywhere
  • 5.Function overloads provide multiple signatures

Interview Tips

  • Explain the difference between void and never
  • Know when to use optional vs default parameters
  • Understand when function overloads are useful

Cheat Sheet

Cheat Sheet

Basic Function Types

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

Optional & Default

function greet(name: string, greeting?: string) {}
function greet(name: string, greeting = "Hello") {}

Rest Parameters

function sum(...nums: number[]): number {
  return nums.reduce((a, b) => a + b, 0);
}

Function Types

type Callback = (data: string) => void;
type Predicate<T> = (item: T) => boolean;

Overloads

function format(input: string): string;
function format(input: number): string;
function format(input: string | number): string { ... }