Skip to content
tezvyn:

TypeScript `infer`: Create a Self-Typing Fetch Wrapper

Source: piccalil.liMediumHow cards are made

TypeScript `infer`: Create a Self-Typing Fetch Wrapper

Use TypeScript's infer to build one fetch wrapper that automatically knows the correct request/response types for every endpoint. It's essential for type-safe calls to APIs with a defined schema.

Why it exists

Manually creating a typed function for every API endpoint is repetitive, error-prone, and hard to maintain. If an API contract changes, developers must hunt down and update types in multiple places. A generic fetch wrapper solves this by centralizing the request logic and deriving all types from a single, authoritative API schema, ensuring consistency and reducing boilerplate.

The mental model

Think of a generic fetch wrapper as a "smart" function that acts as a type-safe contract for your entire API. You give it an endpoint path and an HTTP method, and it consults a master type definition (your API schema) to figure out exactly what kind of data it needs for the request and what kind of data it will return. It's not just a function that makes an HTTP request; it's a guarantee that your data flow is correct at compile time.

How it works

The magic lies in TypeScript's conditional types and the infer keyword. First, you define a comprehensive type that maps all API paths and HTTP methods to their specific request parameters and response shapes. Your generic fetch function then accepts the path and method as generic type arguments. Inside the function's type signature, you use a conditional type like Path extends keyof ApiSchema ? ... : never. Within that condition, you use infer to extract the specific types. For example, ApiSchema[Path][Method] extends { response: infer R } ? R : never tells TypeScript: "If the schema for this path and method has a response property, infer its type, and use that as this function's return type."

When to use it

This pattern is ideal when you have a well-defined API schema, especially one that is auto-generated from a specification like OpenAPI or Swagger. It's perfect for front-end applications built with frameworks like React or Vue that consume a backend API and need strong type safety to prevent runtime errors and improve developer experience with autocompletion.

When not to use it

Avoid this for simple apps with only one or two API endpoints; the setup overhead isn't justified. It is also less effective if your API lacks a consistent, machine-readable schema or if your endpoint responses are highly dynamic and unpredictable, as this makes it difficult to define a useful master type to infer from.

One canonical example

Imagine an API schema type, ApiSpec, for a birdwatching app. It defines paths like /birds and /sightings. A generic function apiFetch<Path extends keyof ApiSpec>(path: Path, ...) can be called like apiFetch('/birds', { method: 'GET' }). Because the type system knows Path is '/birds', it can look up ApiSpec['/birds']['GET'] and infer that the response will be an array of Bird objects. If you tried to POST to /birds with the wrong request body, TypeScript would throw a compile-time error.

Interview question

In a TypeScript self-typing fetch wrapper, what is the key function of the `infer` keyword?

  • a.To extract specific request and response types from a comprehensive API schema based on generic path and method arguments.Correct
  • b.To ensure that API calls are automatically retried if the initial request fails due to type mismatches.
  • c.To automatically generate the master API schema from existing backend code.
  • d.To create new type definitions for API endpoints based on their runtime behavior.
Why?

The `infer` keyword, used within conditional types, allows TypeScript to extract and derive specific request and response types from a larger, predefined API schema based on the generic arguments provided to the fetch wrapper. Option C is incorrect because `infer` consumes an existing schema to derive types, it does not generate the schema itself.

Just read this? Test yourself on what you have been reading.

Read the original → piccalil.li

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on typescript — each one lists the topics its interview covers.

See open roles