TypeScript as AI contracts is a prompting discipline where you define the interfaces and function signatures for a feature before asking an LLM to write the implementation, so the type checker, not code review, catches shape mismatches in the generated code. The most common mistake developers make when prompting AI for TypeScript code is asking the AI to determine the data shape. "Write a function that fetches user profile data", and then wondering why the returned object uses different property names than the rest of the codebase. The fix doesn't depend on which LLM you reach for, because it lives in the compiler.
Types-first prompting flips this. You define exactly what the function should accept and return. The AI's job is to implement the logic that produces that output. TypeScript then verifies that the output has the shape you declared, which isn't the same as correct, as the demonstration below shows. The AI handles the tedious part; you retain control of the contract.
One limit up front. Nothing here measures model behavior: there's no count of correct generations with and without types. What I can show is the half that's checkable, which is what tsc does when an implementation breaks the contract. That demonstration is in the third section, compiled with TypeScript 7.0.2 on November 25, 2026.
What a model guesses without types
Ask an AI to "fetch and display user orders" and it'll generate something like:
// AI-generated without type contract:
async function getUserOrders(userId) {
const response = await fetch(`/api/orders?user=${userId}`);
const data = await response.json();
return data.orders; // returns any[]
}
This looks fine. It compiles without errors on a non-strict config, and that config is rarer than it used to be: since TypeScript 6.0 (March 23, 2026) strict is true by default, and 7.0 keeps it, so a fresh tsconfig rejects the implicit any on userId straight away. An older project that set "strict": false still lets it through. Either way, the return type is the real problem, because response.json() is typed as Promise<any> under every config, and now you have an any[] propagating through your codebase. The component that renders the orders will access order.id, order.date, order.amount, and none of those property names came from your actual API response. Maybe your API returns orderId, createdAt, totalCents. You won't find out until runtime.
Now compare what happens with a type contract in the prompt:
// You define the contract:
interface OrderItem {
sku: string;
quantity: number;
unitCents: number;
}
interface Order {
orderId: string;
userId: string;
createdAt: Date;
totalCents: number;
status: 'pending' | 'processing' | 'shipped' | 'delivered';
items: OrderItem[];
}
interface GetOrdersResult {
orders: Order[];
totalCount: number;
hasMore: boolean;
}
// You write the signature, AI fills in the body:
async function getUserOrders(userId: string): Promise<GetOrdersResult> {
// AI generates this
}
With the interface in the prompt, the model has orderId, createdAt and totalCents in front of it. Does it always use them? I haven't measured that. What's certain is the other half: if the body builds those objects itself with the wrong names, TypeScript fails the build. One hole stays open: a body that ends in return await response.json() compiles clean against Promise<GetOrdersResult>, because json() returns any, and createdAt then arrives as an ISO string, not the Date the contract promises. The parser in Strategy 2 below is what closes that.
With the types written first, a property-name mismatch in a generated body is a compile error. Without them, the same mismatch waits for a runtime error in staging.
What the compiler proves
I took the Order contract above and wrote four bodies a hurried implementation might produce, by hand, then compiled them with tsc 7.0.2 under --strict. No model wrote these, so this says nothing about how often a model makes each mistake. It shows what the checker does when one is made.
interface ApiRow { id: string; user: string; date: string; amount: number }
// A: builds the objects with the API's names, not the contract's
export async function wrongNames(userId: string, rows: ApiRow[]): Promise<GetOrdersResult> {
const orders = rows.map((row) => ({
id: row.id,
userId,
date: new Date(row.date),
amount: row.amount,
status: 'pending' as const,
items: [],
}));
return { orders, totalCount: orders.length, hasMore: false };
}
// B: a status the union doesn't have
export function wrongStatus(order: Order): Order {
return { ...order, status: 'cancelled' };
}
// C: passes the response straight through
export async function passThrough(userId: string): Promise<GetOrdersResult> {
const response = await fetch(`/api/orders?user=${userId}`);
return await response.json();
}
// D: a guard that checks almost nothing
export function isValidOrder(data: unknown): data is Order {
return typeof data === 'object';
}
The compiler's whole answer (line numbers refer to the full file, with the interfaces from the previous section on top):
demo.ts(39,12): error TS2322: Type '{ id: string; userId: string; date: Date; amount: number; status: "pending"; items: never[]; }[]' is not assignable to type 'Order[]'.
Type '{ id: string; userId: string; date: Date; amount: number; status: 'pending'; items: never[]; }' is missing the following properties from type 'Order': orderId, createdAt, totalCents
demo.ts(44,22): error TS2322: Type '"cancelled"' is not assignable to type '"delivered" | "pending" | "processing" | "shipped"'.
Two errors for four mistakes. A and B are caught, and the first message even lists the three names the contract wanted. C and D compile clean. Why? response.json() returns any, and any is assignable to everything, so the annotation on C proves nothing about what arrives. And a data is Order predicate is a promise the compiler takes on trust.
So the thesis needs a qualifier: a type contract turns the mistakes made in typed code into build failures, and does nothing at the two places where types are asserted instead of derived. Those two places are where the patterns below spend their effort.
Four prompting patterns
Pattern 1: Interface-First Implementation
The base pattern. Always define both the input types and the output type before asking for implementation:
I have these TypeScript types:
[paste your interfaces]
Write [function name]([typed params]): Promise<[return type]> that [business rule in one sentence].
The "business rule in one sentence" is important. Don't describe the implementation, describe the contract behavior. "Returns the 10 most recent orders sorted by createdAt descending, filtered to the given userId." The AI handles the how; you define the what.
Pattern 2: Discriminated Union Contracts
Discriminated unions are my pick for the most useful contract type for generated code, because they make impossible states unrepresentable. Define them first:
type ApiResult<T> =
| { status: 'success'; data: T; timestamp: Date }
| { status: 'error'; code: string; message: string }
| { status: 'loading' };
// Prompt: "Write a useOrders hook that returns ApiResult<Order[]>,
// manages the fetch lifecycle, and handles network errors."
When you define a discriminated union, a generated body that skips a case can be made into a compile error: TypeScript's exhaustiveness checking complains, provided the default branch assigns the leftover value to never.
Documentation can drift silently; a type that drifts from the code fails the build. You're forcing correctness through the type system rather than through code review.
Pattern 3: Generic Constraints as Specification
Generics with constraints are dense specifications. Use them for reusable utilities:
// Prompt: "Write a paginate<T extends { id: string }> function
// with this signature:
function paginate<T extends { id: string }>(
items: T[],
cursor: string | null,
limit: number
): { items: T[]; nextCursor: string | null; total: number }
The constraint T extends { id: string } states exactly what any implementation may assume about the items: they have an id property of type string. A body can use item.id for cursor logic. Reach for item.name and the compiler refuses, whoever wrote the line. This is a complete specification in TypeScript syntax.
Pattern 4: Type Guards as Contracts
When you need AI to generate validation code, define the type guard signature first:
function isValidOrder(data: unknown): data is Order {
// Prompt: "Implement this type guard that validates
// all required fields from the Order interface above"
}
A type guard with data is Order tells the AI: you must write a function that returns a boolean, and TypeScript knows that true means the argument is safely typed as Order. The implementation has to actually validate the structure, and nothing checks that it does: if it returns true too early and your code later accesses order.items, TypeScript trusts the guard and the crash happens at runtime. So the guard body is the one piece of generated code you read line by line, or replace with a Zod schema that derives the check from the type.
The four prompting patterns side by side
| Pattern | What you define first | Best for |
|---|---|---|
| Interface-first implementation | Input and output types | Any function with a clear data shape |
| Discriminated union contracts | A tagged union like ApiResult<T> | Forcing exhaustive state handling |
| Generic constraints as specification | A constrained generic like T extends { id: string } | Reusable utilities |
| Type guards as contracts | A data is Order signature | Validation code |
Third-party libraries with loose types
The hardest case is AI-generated code that uses third-party libraries with incomplete or overly broad types. Type narrowing is the process of taking a wide or loosely typed value and constraining it to a more specific shape, either through TypeScript's utility types or through runtime validation with a library like Zod. Two strategies work, and runtime validation is the only one that actually protects you when the third-party library's published types don't match what the API returns at runtime, which happens more often than most teams expect from actively maintained packages. Zod's intro shows the shape of it: parse untrusted input, then work with the validated, typed result.
Strategy 1: Extract narrow types from wide ones
import type { Response } from 'some-library';
// The library's Response is Response<any>. Narrow it:
type TypedResponse<T> = Omit<Response, 'data'> & { data: T };
// Now prompt: "Write a fetchOrders function returning
// TypedResponse<Order[]> using this-library's client"
Strategy 2: Wrap in your types immediately
// Prompt: "Write fetchRaw that calls the third-party API and
// returns unknown. Then write parseOrderResponse(raw: unknown): Order
// using a Zod schema that validates and transforms the raw response."
The parsing function has an explicit output type (Order). Even if the raw API response is unpredictable, a schema-based parser either produces the right output type or throws. Zod makes this pattern clean: the schema and its inferred type can't drift apart, and z.coerce.date() is the line that turns the JSON string back into the Date your Order promises. The compile-time half of the same story is the compiler configuration, which comes next.
Which compiler flags catch what the contract misses?
The contract does its work before generation. The compiler flags do theirs afterwards, when the model got something wrong anyway. Generated code tends to fail in three ways, and each has a different catcher.
| Failure mode | Example | What catches it |
|---|---|---|
| Hallucinated method | array.flatten(), which no array has (the real one is flat()) | The compiler, on the spot |
| Stale API | req.param() in an Express 5 codebase; Node's deprecated url.parse() | The compiler for removed APIs (@types/express 5 has no req.param). A merely @deprecated one still compiles and only gets an editor strikethrough, or a lint error from @typescript-eslint/no-deprecated |
| Optimistic null handling | user.profile.avatar.url with no checks | strict plus noUncheckedIndexedAccess |
strict is the default since 6.0, as noted above. The flags worth adding by hand are still opt-in:
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true
}
}
noUncheckedIndexedAccess earns its place first. A body that assumes the array has items is easy to write and easy to miss in review, and this flag rejects it:
// Generated:
function getFirstUser(users: User[]): string {
return users[0].name; // Error: users[0] is User | undefined
}
// What the flag forces:
function getFirstUser(users: User[]): string | undefined {
return users[0]?.name;
}
noPropertyAccessFromIndexSignature demands bracket notation for dynamic keys, so it's obvious when generated code treats a typed interface like a loose object. noImplicitOverride flags a subclass method that shadows a parent's without the override keyword.
Will this be noisier on day one? Yes, and the noise is the checker finding real problems. Two team rules keep it honest. Type checking runs in CI, so a suggestion that fails it doesn't merge. And // @ts-nocheck is banned, because a model will sometimes add it to make an error go away. If you're auditing an older codebase, look for an explicit "strict": false first. Neither 6.x nor 7.0 overrides it, and deleting that one line does more than any flag in the list.
None of this catches logic. A sort that runs descending when you wanted ascending type-checks fine, and so does a discount applied twice. Types verify structure; tests and a human verify intent.
Compound contracts
Real features need multiple types that reference each other. Define the full graph before prompting:
interface User {
id: string;
email: string;
role: 'admin' | 'member' | 'viewer';
}
interface Permission {
resource: 'orders' | 'users' | 'settings';
action: 'read' | 'write' | 'delete';
}
interface AuthContext {
user: User;
permissions: Permission[];
expiresAt: Date;
}
// Now: "Write canPerform(ctx: AuthContext, resource: Permission['resource'],
// action: Permission['action']): boolean that checks ctx.permissions"
With the full type graph in the prompt, every relationship is stated: what a User looks like, what a Permission contains, how AuthContext composes them. And with the same graph in the file, code that traverses a structure that doesn't exist won't compile. Leave the types out and both of those disappear. A guess that's almost right is the expensive kind, because it reads fine in review.
The types-first workflow, start to finish
For any significant TypeScript feature built with AI, I work in this order:
- Open a
types.tsfile and define all interfaces for the feature - Write function signatures with explicit return types but empty bodies
- Paste the types + signatures into Claude or Copilot with the business rule
- Review the implementation for logic, not types, TypeScript handles type correctness
- Run
tsc --noEmitas the final check
Step 4 is where the habit changes. Type mismatches are the compiler's job, so don't spend review time hunting them. Read for logic: does the pagination actually use the cursor correctly? Does the error path return the right discriminated union variant? Is there an off-by-one in the limit calculation?
You still review every generated body under TypeScript as AI contracts. What the review covers moves from mechanical type checking to reasoning about behavior.
For the quality gate that enforces this workflow on the entire team, see CI/CD quality gates for AI-generated code.