Advanced TypeScript for Harness Builders

7. The `infer` Keyword

Extract a type from a structural position inside a conditional type.

infer extracts a type from a structural position inside a conditional type.

File: packages/ai/src/models.ts L15-18

type ModelApi<TProvider extends KnownProvider, TModelId extends keyof (typeof MODELS)[TProvider]> = (typeof MODELS)[TProvider][TModelId] extends {
  api: infer TApi;
}
  ? TApi extends Api
    ? TApi
    : never
  : never;

This extracts the api field’s type from a specific model entry in the generated models object, then validates it extends Api.

Using Parameters<> and ReturnType<>:

File: packages/agent/src/types.ts L24-26

export type StreamFn = (...args: Parameters<typeof streamSimple>) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;

Parameters and ReturnType use infer internally to extract function signatures.


Open this chapter inside the full course