# Structured Outputs in TypeScript with the AI SDK and Zod

> Stop parsing free-form model text. Define a Zod schema, request an object with Output.object and get validated, typed data back — plus the schema rules that keep strict providers happy.

- Published: 2026-09-23
- Updated: 2026-10-07
- Category: Tutorials
- Type: tutorial
- Tags: ai-sdk, structured-outputs, typescript, zod
- Sources: 4
- Canonical: https://rajatxautomatedcontent.vercel.app/articles/structured-outputs-typescript-ai-sdk-zod

---

## What you will build

A small extractor that turns messy release notes into a typed object — product, version, highlights and breaking changes — that is validated at runtime and typed at compile time. No regular expressions, no `JSON.parse` on free-form model text.

## Prerequisites

- A TypeScript project with the `ai` and `zod` packages.
- A model provider configured for the AI SDK. The examples pass a model id string; swap in whichever provider or model you use.

```bash
npm install ai zod
```

## Step-by-step

### 1. Describe the shape with Zod

Zod lets you declare a schema once and get both a static TypeScript type and runtime validation [S3]. Field descriptions double as guidance for the model.

```ts
import { z } from "zod";

export const releaseNote = z.object({
  product: z.string().describe("Product or library name"),
  version: z.string().describe("Version exactly as written, for example 2.4.0"),
  highlights: z.array(z.string()).max(5),
  breakingChanges: z.array(z.string()),
  requiresMigration: z.boolean(),
});

export type ReleaseNote = z.infer<typeof releaseNote>;
```

### 2. Generate the object

The AI SDK generates structured data through the `output` option of `generateText`: pass `Output.object({ schema })` and the schema is used both to guide generation and to validate the result [S1]. Besides Zod, it also accepts Valibot and JSON Schema definitions [S1].

```ts
import { generateText, Output } from "ai";
import { releaseNote } from "./schema";

export async function extractReleaseNote(changelog: string) {
  const { output } = await generateText({
    model: "anthropic/claude-sonnet-5.5", // any model your provider supports
    instructions: "Extract release information. Use only facts stated in the text.",
    prompt: changelog,
    output: Output.object({ schema: releaseNote }),
  });
  return output; // typed as ReleaseNote
}
```

### 3. Stream partial objects for responsive UIs

For longer outputs, `streamText` accepts the same `output` option and exposes `partialOutputStream`, an async iterable of partial objects [S1]. Partial objects are not validated against the schema, because incomplete data may not match it yet [S1] — validate the final object before you trust it.

```ts
import { Output, streamText } from "ai";
import { releaseNote } from "./schema";

export async function streamReleaseNote(changelog: string, render: (partial: unknown) => void) {
  const { partialOutputStream } = streamText({
    model: "anthropic/claude-sonnet-5.5",
    prompt: changelog,
    output: Output.object({ schema: releaseNote }),
  });

  for await (const partial of partialOutputStream) {
    render(partial); // fields fill in as they arrive
  }
}
```

### 4. Handle failures explicitly

When the model cannot produce a valid object, the SDK throws `NoObjectGeneratedError`. The error carries the generated text, the finish reason and the underlying cause, which makes it useful for logging and targeted retries [S2].

```ts
import { NoObjectGeneratedError } from "ai";
import { extractReleaseNote } from "./extract";

export async function safeExtract(changelog: string) {
  try {
    return await extractReleaseNote(changelog);
  } catch (error) {
    if (NoObjectGeneratedError.isInstance(error)) {
      console.error("Model output did not match the schema", {
        finishReason: error.finishReason,
        text: error.text,
      });
      return null;
    }
    throw error;
  }
}
```

## Schema rules that keep strict providers happy

Some providers enforce a strict subset of JSON Schema. OpenAI's Structured Outputs, for example, requires every field to be required and objects to disallow additional properties; to make a value optional you use a union with `null` [S4]. In Zod terms:

- Prefer `.nullable()` over `.optional()` for values the model may not find.
- Avoid open-ended objects such as `z.record()` in schemas you send to a model.
- Keep nesting shallow, names descriptive, and use `.describe()` to state intent.

## Troubleshooting

| Symptom                         | Likely cause                                        | Fix                                                          |
| ------------------------------- | --------------------------------------------------- | ------------------------------------------------------------ |
| `NoObjectGeneratedError`        | Output did not match the schema                     | Relax constraints, add `.describe()` hints, log `error.text` |
| The provider rejects the schema | Optional fields or open records under a strict mode | Use `.nullable()`, remove records                            |
| Arrays come back empty          | The input simply lacks that data                    | That may be correct — never force a model to invent values   |

## Next steps

- Structured output is only as trustworthy as its inputs. Our [editorial policy](/editorial-policy) explains how every extracted fact on this site is checked against its source.
- Streaming the result to a browser? Compare [Server-Sent Events and WebSockets](/articles/server-sent-events-vs-websockets-llm-streaming).

## FAQ

**Do I have to use Zod with the AI SDK?**

No. The AI SDK also accepts Valibot and JSON Schema definitions. Zod is popular because one definition gives you both TypeScript types and runtime validation.

**Are streamed partial objects validated?**

No. Partial objects cannot be validated because incomplete data may not match the schema yet. Validate the final object before you rely on it.

**Why use nullable instead of optional in schemas?**

Strict structured-output modes, such as OpenAI's, require every field to be present. A nullable field stays required but can hold null when the model finds no value.

## Sources

- [S1] Generating Structured Data — AI SDK. <https://ai-sdk.dev/docs/ai-sdk-core/generating-structured-data> (retrieved 2026-09-30, trust: official)
- [S2] NoObjectGeneratedError — AI SDK. <https://ai-sdk.dev/docs/reference/ai-sdk-errors/ai-no-object-generated-error> (retrieved 2026-09-30, trust: official)
- [S3] Zod: TypeScript-first schema validation — Zod. <https://zod.dev/> (retrieved 2026-09-30, trust: official)
- [S4] Structured model outputs — OpenAI. <https://platform.openai.com/docs/guides/structured-outputs> (retrieved 2026-09-30, trust: official)

---

Source: AI Dev Hub — https://rajatxautomatedcontent.vercel.app/articles/structured-outputs-typescript-ai-sdk-zod
