On this page

Typing Common JavaScript Patterns in TypeScript

Updated on July 27, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

TypeScript does not ask developers to abandon the JavaScript idioms they already rely on — dynamic dictionaries, factory functions, higher-order functions, and callbacks all remain perfectly valid. What changes is that each of these patterns can be described precisely with a type, so the compiler and the editor catch mistakes that would otherwise only surface at runtime. Index signatures and Record type dictionary access, explicit return types and union types describe functions that return objects, generics combined with Parameters and ReturnType preserve type information through higher-order functions, and typed function signatures make callbacks predictable. None of this requires new syntax to learn from scratch — it is the same JavaScript, described more precisely.

This article walks through each of these four patterns individually, explains the reasoning behind the recommended typing approach, and then shows how they combine in realistic code.

Objects as Dictionaries​

JavaScript code frequently uses plain objects as maps or lookup tables, where the set of keys is not known in advance and every value has the same shape:


const scores = {

  alice: 10,

  bob: 20,

};

This works in JavaScript because objects can hold any property name. TypeScript needs an explicit description of that flexibility, which is where index signatures come in.

Defining a Dictionary with an Index Signature​

An index signature tells TypeScript that any key of a given type maps to a value of a given type, without listing the keys individually:


const scores: { [key: string]: number } = {

  alice: 10,

  bob: 20,

};

The [key: string]: number syntax means: "any property whose name is a string must have a value of type number." Assigning scores.charlie = "ten" would fail to compile, because "ten" is a string, not a number, while scores.charlie = 30 is accepted because it satisfies the constraint. The key type can be string, number, or symbol — string is by far the most common choice, since JavaScript coerces every object key to a string internally anyway.

Using Record for Cleaner Dictionary Types​

The built-in Record<K, V> utility type expresses the same constraint with less syntax and is generally the preferred style for straightforward dictionaries:


const scores: Record<string, number> = {

  alice: 10,

  bob: 20,

};

Record<string, number> and { [key: string]: number } are structurally equivalent — they produce the same type. Record reads more clearly at a glance and is easier to reuse as a named type alias:


type ScoreMap = Record<string, number>;



function getAverage(scores: ScoreMap): number {

  const values = Object.values(scores);

  return values.reduce((sum, n) => sum + n, 0) / values.length;

}

Record also supports a union of string literals as the key type, which is useful when the dictionary should only ever contain a fixed, known set of keys rather than arbitrary strings:


type Environment = "development" | "staging" | "production";



const apiUrls: Record<Environment, string> = {

  development: "http://localhost:3000",

  staging: "https://staging.example.com",

  production: "https://api.example.com",

};

With this version, TypeScript requires all three keys to be present and rejects any key outside the Environment union — a stricter guarantee than a plain string index signature would give.

Dictionaries of Objects​

The value type in a dictionary is not limited to primitives. A dictionary can hold complex object shapes just as easily:


type User = { id: number; name: string };



const users: Record<string, User> = {

  a1: { id: 1, name: "Alice" },

  b2: { id: 2, name: "Bob" },

};

Every value stored under any key in users is checked against the User type. Accessing users.a1.name gives full autocomplete for the User shape, and assigning an object missing the name property is rejected at compile time.

Immutable Dictionaries​

When a dictionary should never be modified after creation — a set of configuration values loaded once at startup, for example — wrap it in Readonly:


const config: Readonly<Record<string, string>> = {

  region: "eu-west-1",

  tier: "production",

};



config.region = "us-east-1"; // compile-time error: read-only property

Readonly<Record<K, V>> prevents both adding new keys and reassigning existing ones after the object is created, which is useful for values that should behave as constants throughout the application's lifetime.

Why Typing Dictionaries Matters​

Functions That Return Objects​

Factory functions, configuration builders, and API response wrappers are among the most common places where JavaScript functions return object literals:


function createUser(name: string, age: number) {

  return { name, age };

}

Letting TypeScript Infer the Return Type​

TypeScript examines the return statement and infers the shape automatically, without requiring any annotation:


function createUser(name: string, age: number) {

  return { name, age };

}

// inferred return type: { name: string; age: number }

Inference is convenient for internal helper functions where the shape is obvious from the function body and unlikely to need independent documentation.

Declaring an Explicit Return Type​

For functions that form part of a public API — exported from a module, consumed by other files, or used across a team — an explicit return type is worth the extra line. It documents the contract clearly and produces an error at the function definition itself if the implementation drifts from what was promised, rather than surfacing confusingly at the call site:


type User = {

  name: string;

  age: number;

};



function createUser(name: string, age: number): User {

  return { name, age };

}

If a future edit to createUser accidentally omits the age property, the error appears directly on the return statement inside createUser, not somewhere downstream where the missing property is first used.

Returning Different Shapes with Union Types​

A function sometimes needs to return one of several distinct shapes depending on what happens during execution — a classic case is a function that either succeeds with data or fails with an error message. Union types combined with a shared, differently-valued property (commonly called a discriminant) model this precisely:


type Success = { ok: true; data: string };

type Failure = { ok: false; error: string };



function load(): Success | Failure {

  if (Math.random() > 0.5) {

    return { ok: true, data: "Loaded!" };

  }

  return { ok: false, error: "Failed" };

}

Because ok is true in one member of the union and false in the other, TypeScript can narrow the type automatically based on a simple check:


const result = load();



if (result.ok) {

  console.log(result.data); // result is narrowed to Success here

} else {

  console.log(result.error); // result is narrowed to Failure here

}

Inside the if (result.ok) branch, TypeScript already knows result is a Success, so result.data is accessible without any type assertion, and result.error would correctly be flagged as not existing on that branch. This pattern — a union of object types sharing one property whose value differs across the members — is known as a discriminated union, and it is one of the most useful tools TypeScript offers for modeling functions with multiple possible outcomes.

The satisfies Operator as an Alternative​

For object literals assigned directly to a variable (rather than returned from a function), the satisfies operator offers a way to validate the shape against a type while keeping the more specific inferred type for later use:


const user = {

  name: "Alice",

  age: 25,

} satisfies { name: string; age: number };

satisfies checks that user conforms to the given type — a missing or mistyped property is caught immediately — while still letting TypeScript retain the literal, narrower type of user for anything downstream that depends on its exact shape. This is a complementary tool to explicit return types on functions, useful specifically for standalone object literals and configuration objects.

Higher-Order Functions​

A higher-order function either accepts a function as an argument, returns a function, or both. map, filter, middleware layers, decorators, and event wrappers are all higher-order functions, and they appear constantly in day-to-day JavaScript code.

Typing a Basic Higher-Order Function​


function withLogging<T>(fn: (value: T) => T) {

  return (value: T) => {

    console.log("Calling with:", value);

    return fn(value);

  };

}

<T> introduces a generic type parameter. Rather than hardcoding a specific type for the wrapped function, T is filled in automatically based on the function passed at the call site:


const double = (n: number) => n * 2;

const loggedDouble = withLogging(double);



loggedDouble(10); // fine — T is inferred as number

loggedDouble("hi"); // compile error — "hi" is not a number

When withLogging(double) is called, TypeScript infers T as number from the type of double, and that inference carries through to the returned wrapper function. Calling loggedDouble("hi") afterward fails to compile, because the wrapper's parameter type was locked to number at the moment it was created.

Preserving Types Across Multiple Parameters​

The same generic approach extends naturally to functions with more than one parameter:


function wrap<A, B>(fn: (a: A, b: B) => void) {

  return (a: A, b: B) => {

    console.log("Wrapped call");

    fn(a, b);

  };

}

Each type parameter — A and B — is inferred independently from the function passed in, and both are preserved on the returned wrapper.

Using Parameters and ReturnType to Generalize Wrappers​

Writing a new generic signature by hand for every possible function shape does not scale. The built-in Parameters<T> and ReturnType<T> utility types extract a function's parameter tuple and return type respectively, which makes it possible to write a wrapper that works with any function shape without repeating its signature manually:


function withTiming<T extends (...args: any[]) => any>(fn: T) {

  return (...args: Parameters<T>): ReturnType<T> => {

    const start = performance.now();

    const result = fn(...args);

    console.log("Took", performance.now() - start, "ms");

    return result;

  };

}

T extends (...args: any[]) => any constrains T to be some kind of function, which is required before Parameters<T> and ReturnType<T> can be applied to it. Parameters<T> produces a tuple type matching fn's exact parameter list, and ReturnType<T> produces its exact return type. The wrapper returned by withTiming therefore has precisely the same call signature as whatever function was passed in — arguments are checked correctly, and the return value keeps its original type, all without writing out the specific signature by hand.

Why Typing Higher-Order Functions Matters​

Callback Patterns​

Callbacks appear throughout JavaScript: event handlers, asynchronous completions, array iteration methods, and custom utility functions all rely on a function being passed in and invoked later.

Typing a Basic Callback​


function repeat(n: number, callback: (i: number) => void) {

  for (let i = 0; i < n; i++) {

    callback(i);

  }

}



repeat(3, (i) => console.log(i));

The callback: (i: number) => void annotation describes exactly what repeat expects: a function taking one number argument and returning nothing meaningful. When calling repeat, TypeScript already knows the shape of the callback it needs, so the arrow function (i) => console.log(i) does not need its own type annotation — i is inferred as number from context.

Callbacks That Return a Value​

A callback used with something like Array.prototype.map needs to describe both what it receives and what it produces:


function mapNumbers<T>(arr: number[], fn: (n: number) => T): T[] {

  return arr.map(fn);

}

T represents whatever type the callback returns — a string, a boolean, another object shape — and mapNumbers returns an array of that same type. Calling mapNumbers([1, 2, 3], (n) => n.toString()) produces a string[], while mapNumbers([1, 2, 3], (n) => n > 1) produces a boolean[], without mapNumbers itself needing separate versions for each case.

Callbacks with Object Parameters​

Callback parameters are not limited to primitives — a callback frequently receives a full object:


type User = { id: number; name: string };



function forEachUser(users: User[], fn: (user: User) => void) {

  users.forEach(fn);

}

Any callback passed to forEachUser receives a fully-typed User object as its argument, with autocomplete available for id and name inside the callback body.

Callbacks with Multiple Arguments​

A callback can also accept more than one argument, mirroring the native array method signatures it is meant to complement:


function filterWithIndex<T>(

  arr: T[],

  fn: (value: T, index: number) => boolean,

): T[] {

  return arr.filter((value, index) => fn(value, index));

}

fn here receives both the current element and its index, matching the shape that Array.prototype.filter itself provides. Wrapping the native callback this way still enforces that anything passed to filterWithIndex returns a boolean, since that is what .filter requires to decide inclusion.

Why Typing Callbacks Matters​

Combining the Patterns in Real Code​

These four patterns rarely appear in isolation. A realistic module typically combines a dictionary, a factory function, a higher-order function, and a callback together:


type User = { id: number; name: string };



// Dictionary of users

const userMap: Record<string, User> = {};



// Higher-order function using Parameters and ReturnType

function withTiming<T extends (...args: any[]) => any>(fn: T) {

  return (...args: Parameters<T>): ReturnType<T> => {

    const start = performance.now();

    const result = fn(...args);

    console.log("Took", performance.now() - start, "ms");

    return result;

  };

}



// Function returning an object

function createUser(id: number, name: string): User {

  return { id, name };

}



// Callback pattern

function processUsers(users: User[], fn: (u: User) => void) {

  users.forEach(fn);

}

userMap is a typed dictionary keyed by string, holding User objects. withTiming is a higher-order function that wraps any function while preserving its exact parameter and return types through Parameters<T> and ReturnType<T>. createUser is a factory function with an explicit User return type. processUsers accepts a callback typed against the same User shape used everywhere else in the module. None of these four pieces needs to know about the internal implementation of the others — they interoperate correctly because they all reference the same User type.

Recognizing These Patterns in Practice​

Dictionaries, factory functions, higher-order functions, and callbacks are not TypeScript-specific constructs — they are ordinary JavaScript idioms that TypeScript describes with more precision. An index signature or Record<K, V> covers dynamic key-value data. Explicit return types and discriminated unions cover functions that hand back structured data, including functions with more than one possible outcome. Generics paired with Parameters<T> and ReturnType<T> let a wrapper function preserve the exact signature of whatever it wraps. Typed callback parameters make array iteration and event-driven code predictable to both write and consume.

These typing techniques remain stable across current TypeScript releases; ongoing changes to the TypeScript toolchain — including the compiler's move to a native implementation — affect build performance and tooling internals, not the syntax used to express these patterns in application code.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Common TypeScript Usage Patterns

Next

Working with DOM & Browser APIs