# Write precise TypeScript types for my data and APIs

Safer, readable TypeScript types that rule out impossible states, replace unsafe casts, and come with compile-time tests.

- Topic: Software Development
- Framework: Few-Shot
- Level: Advanced
- Tags: Coding, Write, Code, Fill-in Template
- Source: https://www.thinkwithprompt.com/prompts/write-precise-typescript-types-for-my-data-and-apis

## Prompt

```text
Help me design precise, maintainable TypeScript types for my code.

**What I'm typing:** [e.g. "API responses", "a reducer's state and actions", "a form library", "a config object"]
**Current code or types:** [PASTE]
**TypeScript version and settings:** [VERSION, strict mode on or off, framework]
**Pain points:** [e.g. "too many any types", "impossible states are allowed", "generics are unreadable", "slow type-checking"]

Aim for:
- **Impossible states can't be represented:** use discriminated unions instead of optional flags (e.g. `{ status: "loading" } | { status: "success"; data: T } | { status: "error"; error: E }`).
- **Narrow, don't cast:** replace `as` assertions with type guards, `satisfies`, or validation at the boundary. For untrusted data (APIs, user input), recommend runtime validation with a schema library and derive the types from the schema.
- **Generics with purpose:** constrain type parameters, name them clearly, and avoid generics callers must spell out by hand.
- **Advanced types only when they pay off:** mapped, conditional, and template literal types and `infer`, each non-obvious one with a short comment.
- **Exhaustiveness:** `never` checks in switch statements over unions.
- **Compiler performance:** avoid deeply recursive types that slow type-checking.

Return:
1. The revised types in a code block, with brief comments.
2. A table: Problem | Fix | Why it's safer.
3. Usage examples that should compile and ones that should fail, marked with `// @ts-expect-error`.
4. Any changes needed in calling code.

If something can't be typed safely without a runtime check, say so instead of forcing it.
```

## What to fill in

- PASTE
- VERSION, strict mode on or off, framework

Free to copy and use. From ThinkWithPrompt (https://www.thinkwithprompt.com/), a library of 2,663 curated AI prompts.
