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.
The prompt
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.
Highlighted [brackets] are blanks to replace with your own details.
Fill in the blanks and use this promptMore Software Development prompts
What to fill in
- PASTE
- VERSION, strict mode on or off, framework
How this prompt is built
This prompt follows the Few-Shot structure (Few-shot prompting). A few-shot prompt includes one or more worked examples of the input and the output you want, so the model can copy the pattern instead of guessing it.
Related prompts
- Write a style guide that documents my app's existing design codeReverse-engineers colors, typography, spacing, and component patterns from your codebase into a STYLE_GUIDE.md developers and AI agents can follow.
- Write a Semgrep rule to catch a risky code patternProduces a working Semgrep rule with test cases, so you can block a bug or security pattern across your codebase.
- Find and fix a race condition or concurrency bugAnalyzes code for race conditions, deadlocks, and lost updates, explains the exact interleaving that fails, and proposes a safe fix.
- Write documentation, a README, or API docsGenerates clear technical documentation from your code or notes.