TypeScript Generics in Practice: From Replacing any and const/NoInfer to Typed fetch, Store, and tsc Error DebuggingLongread · digest for November 30
Infographic patent drawing of a type parameterization and generics system with geometric slots and compiler inspection gauges
Longread6 sections≈ 24 min

TypeScript Generics in Practice: From Replacing any and const/NoInfer to Typed fetch, Store, and tsc Error Debugging

Whenever a TypeScript function needs to accept strings, numbers, and objects, it's tempting to reach for any. At first glance, everything looks great: the compiler stays quiet, red squiggles disappear, and the build passes. In reality, any just cuts the wire between a function's input and output. Editor autocomplete goes silent, a typo in a property name sails through compilation, and the bug surfaces in the browser or on the server.

Generics solve that exact problem. They let you write logic once while preserving the link between what goes into the arguments and what comes back out. Below, we'll walk through the whole path—from a tiny function and basic syntax to const and NoInfer modifiers, conditional types, three runnable Node.js 24 modules, and a tsc error cheat sheet. Every example was verified in strict mode on TypeScript 7.0.2 (the stable native Go port released in August 2026 that speeds up builds 8–12x) and TypeScript 6.0.3, the final JS branch from March 2026.

Why You Need a Type Parameter and How Basic Syntax Works

A type parameter in angle brackets <T> works like a regular variable, except it holds a type instead of a value. The compiler computes it when the function is called and carries it into the return type. People use T by convention, though you're free to write Type, Item, or any clear name.

Let's compare any and a generic in the shortest possible example, identity.ts:

// any cuts the link between argument and return value
function identityAny(arg: any): any {
  return arg;
}

// T captures the argument type and returns the same type
function identity<T>(arg: T): T {
  return arg;
}

export const a = identityAny("hello");
export const b = identity("hello");
export const c = identity<string>("hello");

Instead of guessing what the compiler inferred, ask tsc to emit a .d.ts declaration file and look inside. Create an empty folder, save identity.ts, and run four commands:

npm init -y
npm i -D typescript@7.0.2
node node_modules/typescript/bin/tsc \
  --ignoreConfig --strict --declaration \
  --emitDeclarationOnly --outDir out identity.ts
cat out/identity.d.ts

--ignoreConfig ignores any accidental tsconfig.json in parent folders, --strict enables strict checks, --declaration with --emitDeclarationOnly outputs only types without JS files, and --outDir out writes them to out. Inside out/identity.d.ts, you'll see three lines:

export declare const a: any;
export declare const b = "hello";
export declare const c: string;

The difference is crystal clear. Variable a has type any, so you can call a.nonExistentMethod() and the compiler won't blink. Variable b got the literal type "hello"—not just an abstract string, but that exact value. For c, we passed <string> explicitly, so the compiler widened the result to a regular string.

In TypeScript, angle brackets appear in five main places: functions, arrow functions, interfaces, type aliases, and classes. On functions, interfaces, type aliases, and classes, the parameter goes right after the name; on arrow functions, it goes before the argument parentheses:

// Regular function
function first<T>(items: T[]): T | undefined {
  return items[0];
}

// Arrow function: trailing comma after T prevents JSX errors in .tsx
const firstArrow = <T,>(items: T[]): T | undefined => {
  return items[0];
};

// API response interface
interface ApiResponse<T> {
  data: T;
  error?: string;
}

// Type alias with a default type parameter
type Pair<A, B = A> = [A, B];

// Class constrained to object types
class Box<T extends object> {
  value?: T;
}

export const p: Pair<number> = [1, 2];
export const r: ApiResponse<string[]> = { data: ["a"] };

That odd comma in <T,> on the arrow function isn't a typo. In .tsx files, without it, the parser mistakes <T> for an opening JSX tag and throws a syntax error. It works in plain .ts files too, so it's a good habit to build early. Meanwhile, B = A sets a default type parameter: if you pass only one type to Pair<number>, the second defaults to number. Just like regular function parameters, defaults always go after required ones.

Constraints with extends, keyof, and the Empty Array Trap

As long as a generic is unconstrained, the compiler assumes T could be anything—even a number or null. That's why you can't just access an object field or look up a property by key. To tell the compiler what shape of data to expect, use T extends X, which only allows types compatible with X.

The workhorse pattern in everyday code is K extends keyof T paired with indexed access T[K]. The keyof operator builds a union of all keys of an object type: for { x: number; y: number }, it produces "x" | "y". One neat quirk with index signatures like { [k: string]: boolean }: keyof returns string | number because JavaScript coerces numeric object keys to strings anyway.

Let's save a property reader to keyof.ts and check it with tsc. --noEmit skips writing files to disk, and --pretty false prints errors on a single clean line:

Wooden block puzzle with shaped slots illustrating strict type constraints extends and keyof

function getProperty<T, K extends keyof T>(
  obj: T,
  key: K
): T[K] {
  return obj[key];
}

const user = { name: "Анна", age: 30 };
export const age = getProperty(user, "age");
// user has no email field — compiler catches it immediately
getProperty(user, "email");

Run the check with one command (you can reuse this for the rest of the error examples by swapping the filename at the end):

node node_modules/typescript/bin/tsc \
  --ignoreConfig --strict --noEmit --pretty false keyof.ts

On the "email" line, the compiler stops the build and tells you the exact keys allowed on that object:

keyof.ts(11,19): error TS2345: Argument of type '"email"'
  is not assignable to parameter of type '"age" | "name"'.

Meanwhile, age is inferred accurately as number with zero type assertions. If you remove extends keyof T (index.ts), tsc refuses to compile the function itself because it can't guarantee key K exists on T:

function getValue<T, K>(obj: T, key: K) {
  return obj[key];
}

The terminal immediately throws TS2536, warning that an arbitrary type K can't index T:

index.ts(2,10): error TS2536: Type 'K' cannot be used
  to index type 'T'.

extends works the same way in type aliases. If you define Id<T extends string | number> and pass boolean (constraint.ts), you get TS2344:

type Id<T extends string | number> = { id: T };
type Bad = Id<boolean>;

The compiler output points straight at the broken constraint and the offending type:

constraint.ts(2,15): error TS2344: Type 'boolean' does not
  satisfy the constraint 'string | number'.

At this point, people usually ask: if TypeScript infers types so well on its own, why ever write angle brackets at the call site?

Nine times out of ten, you don't need to. Occasionally, though, the compiler has nowhere to infer the type from, or inference comes back too narrow. The classic example is an empty array:

function first<T>(items: T[]): T | undefined {
  return items[0];
}

export const empty = first([]);
export const empty2 = first<number>([]);

If you generate .d.ts output with the same tsc command, you'll see how the inferred types differ:

export declare const empty: undefined;
export declare const empty2: number | undefined;

In the first call, [] has no elements, so the compiler infers T as never—an empty type with no valid values. never | undefined collapses to plain undefined. Once we pass <number> explicitly, the variable gets number | undefined, which we can actually work with. The same happens when no data exists in the arguments at all, such as a network request function that only takes a URL.

Preserving Literals and Blocking Bad Inference: const and NoInfer

Default type inference in TypeScript can also be too wide. Pass an array of specific names ["Alice", "Bob", "Eve"] into a function, and you get back a generic string[]. Previously, callers had to tack as const onto every argument. TypeScript 5.0 moved that job into the function definition using a const modifier before the type parameter.

Compare two nearly identical functions:

type HasNames = { names: readonly string[] };

// Default inference widens the array to string[]
function getNames<T extends HasNames>(arg: T): T["names"] {
  return arg.names;
}

// The const modifier preserves a literal tuple
function getNamesExactly<const T extends HasNames>(
  arg: T
): T["names"] {
  return arg.names;
}

export const names1 = getNames({
  names: ["Alice", "Bob", "Eve"],
});
export const names2 = getNamesExactly({
  names: ["Alice", "Bob", "Eve"],
});

Checking the generated .d.ts reveals what the compiler kept in each call:

export declare const names1: string[];
export declare const names2: readonly ["Alice", "Bob", "Eve"];

names2 becomes a tuple—a fixed-length array where every position has an exact string literal type. There are two subtleties with const, though. First, it only works on literals passed directly into the function call. If you save the object to a variable first (inferred as { names: string[] }) and pass that variable to getNamesExactly, const can't recover the original strings and leaves string[]. Second, in TypeScript 6.0.3 and 7.0.2, even a mutable names: string[] constraint (without readonly) infers a tuple for direct literal calls, just without readonly.

Another common inference trap happens when an extra argument widens a type instead of being checked against it. Imagine a traffic-light function that takes a list of allowed colors and an optional default color. If you pass ["red", "yellow", "green"] and accidentally write "blue" as the default, you want an error. Without extra guidance, TypeScript lumps all the strings together, decides C is "red" | "yellow" | "green" | "blue", and lets the bug pass.

TypeScript 5.4 introduced the built-in NoInfer<T> utility for this. It stops the compiler from inferring T from a specific argument, forcing it to infer from other positions (noinfer.ts):

function createStreetLight<C extends string>(
  colors: C[],
  // Type C is inferred only from the colors array
  defaultColor?: NoInfer<C>
) {}

createStreetLight(["red", "yellow", "green"], "blue");

Run tsc, and you get the exact error you wanted—the compiler checks "blue" against the first argument's color list:

noinfer.ts(7,47): error TS2345: Argument of type '"blue"'
  is not assignable to parameter of type
  '"green" | "red" | "yellow" | undefined'.

Before NoInfer<C>, developers relied on cryptic tricks like C & {}. Now the intent is obvious at a glance: the array defines valid options, and the second argument must match one of them.

Conditional and Mapped Types: How infer, Awaited, and Partial Work

This section goes a bit deeper—if angle brackets are brand new to you, feel free to skim it and come back later. Still, this is where TypeScript's built-in utility types get their power.

Conditional types look like a ternary operator: T extends U ? X : Y. If T is assignable to U, you get X; otherwise Y. The infer keyword inside the condition lets you extract a piece of the tested type into a new local type variable.

Here's how to pull an array's element type or a function's return type in one line:

// Extracts the element type if an array is passed
type ElementType<T> = T extends readonly (infer U)[]
  ? U
  : T;

// Extracts a function's return type or falls back to never
type ReturnOf<F> = F extends (...args: any[]) => infer R
  ? R
  : never;

type IsString<T> = T extends string ? "да" : "нет";

type E1 = ElementType<number[]>; // number
type E2 = ElementType<string>; // string
type R1 = ReturnOf<() => Promise<boolean>>; // Promise<boolean>
type U1 = Awaited<R1>; // boolean
type D = IsString<"a" | 1>; // "да" | "нет"

In ReturnOf, (...args: any[]) matches a function with any arguments, infer R captures its return type, and never is returned if F isn't a function. The built-in Awaited unwraps a Promise to get the resolved value. Finally, IsString<"a" | 1> shows a distributive conditional type: when a naked type parameter T sits on the left of extends, TypeScript runs the check on each union member separately. "a" yields "да" and 1 yields "нет", producing "да" | "нет".

Now for mapped types. They loop over the keys of an object type and build a new type from it. That's how TypeScript's built-in utility types work under the hood: Partial<T> is { [P in keyof T]?: T[P] }, Readonly<T> is { readonly [P in keyof T]: T[P] }, and Record<K, T> is { [P in K]: T }.

You can write your own Partial clone in a couple of lines:

type Todo = {
  id: number;
  title: string;
  completed: boolean;
};

// Loop over every key K and mark the property optional
type Optional<T> = { [K in keyof T]?: T[K] };

export const draft: Optional<Todo> = {
  title: "Проверить типы",
};

Here K steps through every key of Todo, ? makes the property optional, and T[K] preserves the original value type. In real code, there's no reason to reinvent Optional when Partial, Readonly, Pick, Omit, Record, and Awaited are built in. Knowing there's no magic inside them just makes reading other people's types much easier.

Three Runnable Modules in Node.js 24: fetch, Store, and Emitter

Theory is great, but generics shine in practical wrappers: network requests, state stores, and event buses. All three modules below can be type-checked with tsc and run directly with node, without a build step or third-party tools like ts-node.

Starting with Node.js 24 (these examples use 24.21.0), built-in type stripping is enabled by default. Under the hood, SWC/Amaro replaces type annotations with spaces so stack-trace line numbers match your original .ts file. Keep two caveats in mind: first, Node.js doesn't check types and ignores tsconfig.json, so you still need tsc --noEmit. Second, only erasable syntax works—enum, constructor parameter properties, and namespace blocks with runtime code throw a SyntaxError (and --no-strip-types disables the mode altogether).

Isometric model of a modular station with three working units: fetch, Store, and Emitter

First, here are the commands to type-check and run all three files (fetch.ts, store.ts, and emitter.ts):

node --version
node node_modules/typescript/bin/tsc \
  --ignoreConfig --strict --noEmit \
  --target es2022 --lib es2022,dom \
  --exactOptionalPropertyTypes \
  fetch.ts store.ts emitter.ts
node fetch.ts
node store.ts
node emitter.ts

Once tsc passes with zero errors, each script runs directly and prints its output. Let's walk through all three.

The first module is typed fetch (fetch.ts). When wrapping requests, you want to return either { ok: true, data } or { ok: false, status }. The compiler can't guess the JSON shape from a url string, so <T> is passed at the call site. Here lies the most dangerous habit in TypeScript codebases:

type ApiResult<T> =
  | { ok: true; data: T }
  | { ok: false; status: number };

async function request<T>(
  url: string,
  init?: RequestInit
): Promise<ApiResult<T>> {
  const res = await fetch(url, init);
  if (!res.ok) return { ok: false, status: res.status };
  // as T performs zero validation at runtime
  return { ok: true, data: (await res.json()) as T };
}

type Todo = {
  id: number;
  title: string;
  completed: boolean;
};

// Type guard checks the fields at runtime
function isTodo(value: unknown): value is Todo {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    typeof value.id === "number" &&
    "title" in value &&
    typeof value.title === "string" &&
    "completed" in value &&
    typeof value.completed === "boolean"
  );
}

async function showTodo(url: string) {
  // Request external API data as unknown, not directly as Todo
  const r = await request<unknown>(url);
  if (!r.ok) {
    console.log("HTTP", r.status);
  } else if (isTodo(r.data)) {
    console.log(r.data.title.toUpperCase());
  } else {
    console.log("Неожиданный формат ответа");
  }
}

const json = JSON.stringify({
  id: 1,
  title: "Проверить типы",
  completed: false,
});
void showTodo(
  `data:application/json,${encodeURIComponent(json)}`
);

To keep the example self-contained without a local server, fetch reads JSON from a data: URL while encodeURIComponent escapes special characters. The void operator tells the compiler and linter that we intentionally aren't awaiting the returned promise. The console prints ПРОВЕРИТЬ ТИПЫ. The status branch catches non-2xx HTTP errors, while network failures and invalid JSON still reject the promise.

Why request<Todo>(url) Without Validation Is Risky

Writing (await res.json()) as T is just an honor-system promise to the compiler. TypeScript validates nothing at runtime. If the backend renames title to name, your code crashes on .toUpperCase(). Fetch external data as unknown and run it through a type predicate like isTodo—only then does the compiler safely narrow r.data to Todo.

The second module is a state store with partial updates (store.ts). It combines four tools: T extends object, an ES2022 private #state field, K extends keyof T for reads, and Partial<T> with Readonly<T>:

class Store<T extends object> {
  #state: T;

  constructor(initial: T) {
    this.#state = initial;
  }

  get<K extends keyof T>(key: K): T[K] {
    return this.#state[key];
  }

  // Partial<T> lets you pass only changed fields
  update(patch: Partial<T>): void {
    this.#state = { ...this.#state, ...patch };
  }

  // Readonly<T> prevents mutating properties via this reference
  snapshot(): Readonly<T> {
    return this.#state;
  }
}

const settings = new Store({ theme: "dark", fontSize: 14 });
settings.update({ fontSize: 16 });
console.log(settings.get("fontSize"), settings.snapshot());

Running node store.ts prints 16 { theme: 'dark', fontSize: 16 }. If you try passing a string instead of a number in settings.update({ fontSize: "16" }), the compiler immediately reports error TS2322: Type 'string' is not assignable to type 'number'.

Notice the --exactOptionalPropertyTypes flag in our command (available since TypeScript 4.4). Without it, Partial<T> allows { fontSize: undefined }, and { ...this.#state, ...patch } quietly overwrites the numeric field with undefined at runtime. With this flag enabled, you can omit a property, but you can't explicitly assign undefined unless undefined is part of its type. One honest caveat: snapshot() returns a reference to #state, and Readonly<T> only applies at compile time and only at the top level—nothing is frozen at runtime.

The third module is a typed event bus (emitter.ts). Here the event name automatically determines the payload type in the handler callback:

type Events = {
  login: { userId: number };
  logout: undefined;
  message: { from: string; text: string };
};

class Emitter<E extends Record<string, unknown>> {
  // Object.create(null) avoids prototype keys like toString
  #handlers: {
    [K in keyof E]?: Array<(payload: E[K]) => void>;
  } = Object.create(null);

  on<K extends keyof E>(
    name: K,
    cb: (payload: E[K]) => void
  ): void {
    // ??= creates the listener array on first subscription
    (this.#handlers[name] ??= []).push(cb);
  }

  emit<K extends keyof E>(name: K, payload: E[K]): void {
    // ?. calls forEach only if listeners exist
    this.#handlers[name]?.forEach((cb) => cb(payload));
  }
}

const bus = new Emitter<Events>();
bus.on("message", (m) => {
  console.log(`${m.from}: ${m.text}`);
});
bus.emit("message", { from: "Анна", text: "Привет" });

node emitter.ts outputs Анна: Привет. The Record<string, unknown> constraint defines an "event name -> payload type" map, while Object.create(null) creates a clean dictionary without Object.prototype so events named toString or constructor won't break internals. The callback argument m is inferred automatically from "message". Add a field typo at the bottom:

bus.on("login", (e) => e.userName);

And tsc catches it right away: error TS2339: Property 'userName' does not exist on type '{ userId: number; }'.

tsc Error Cheat Sheet and Common Questions About Generics

When you start writing generic code regularly, compiler messages can look intimidating at first. In practice, almost everything boils down to four error codes. Here are the first lines of TypeScript 7.0.2 output, their usual cause, and the quick fix.

CodeFirst Line of tsc OutputCommon CauseHow to Fix
TS2322Type 'string' is not assignable to type 'T'.Function returns a concrete type instead of TReturn a value of type T or remove the unnecessary generic
TS2344Type 'boolean' does not satisfy the constraint 'string | number'.Passed type doesn't match the extends constraintPass a compatible type or widen the constraint
TS2345Argument of type '"email"' is not assignable to parameter of type '"age" | "name"'.Argument isn't in the inferred union or key listFix the passed value or the source object's type
TS2536Type 'K' cannot be used to index type 'T'.Using obj[key] without a key constraintAdd K extends keyof T to the signature

TS2322 inside a generic function is the most frequent stumbling block. Suppose you write a stub in default.ts:

function makeDefault<T>(): T {
  return "";
}

The compiler refuses to build it and prints two diagnostic lines, where the second explains the core conflict:

default.ts(2,3): error TS2322: Type 'string' is not
  assignable to type 'T'.
  'T' could be instantiated with an arbitrary type which
  could be unrelated to 'string'.

That second line sums up TypeScript's reasoning. A caller has every right to write makeDefault<number>(), expecting a number, while your function always returns an empty string. Either the function must accept a default value from outside, or it always returns a string—in which case it doesn't need a generic at all.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 12