TypeScript Types Prompt for Safer Code
A structured prompt that derives precise types from sample data or API responses, with generics where they pay off — with a real example.
Enhanced prompt — ready to use
ROLE You are a senior TypeScript developer with expertise in type system design. Your goal is to create precise and robust TypeScript types that accurately represent the given data structure. TASK Analyze the provided data structure and define appropriate TypeScript types that ensure type safety and clarity. Think through this step by step, considering edge cases and possible variations in the data. CONTEXT The user requires TypeScript type definitions for their data. Assume the data is a JSON-like object or array with nested properties. The types should be clear and maintainable for a developer audience familiar with TypeScript. REQUIREMENTS - Create TypeScript interfaces or type aliases based on the given data structure. - Include optional properties, unions, or generics if applicable to describe data variations accurately. - Think step by step. Consider edge cases such as nullable fields, arrays, or nested objects. - Before finalizing, verify your answer for correctness and completeness. Assumptions: The data structure is not provided explicitly, so assume a typical nested JSON object with diverse property types. OUTPUT FORMAT Provide the TypeScript type definitions as code blocks with explanatory comments as needed.
That's what PromptAI produced from this vague prompt: “write typescript types for my data”
Example result
```typescript
/**
* The following TypeScript type definitions model a typical nested JSON-like data structure
* containing various property types including primitives, arrays, nested objects,
* optional and nullable fields, and discriminated unions.
*
* These types aim to be precise and maintainable, reflecting common real-world data structures.
*/
/**
* Fundamental scalar types: Possible primitives found in JSON
*/
type Scalar = string | number | boolean | null;
/**
* A flexible value type for properties that accept scalars or arrays of scalars.
*/
type ScalarOrArray<T extends Scalar> = T | T[];
/**
* A common structure for an address, adapted to be optional
*/
interface Address {
street: string;
city: string;
state?: string; // Optional state or province
postalCode?: string | null; // Could be missing or explicitly null
country: string;
}
/**
* A basic user information object, with some optional and nullable fields
*/
interface User {
id: string | number; // ids might be numeric or string
name: string;
email?: string | null; // email might be missing or null (unknown)
phoneNumbers?: string[]; // optional array of phone numbers
address?: Address; // nested object, optional
metadata?: Record<string, unknown>; // optional extra info, unknown values
}
/**
* Base interface for an Item; it's extended by specialized item types below
*/
interface BaseItem {
id: string;
createdAt: string; // ISO date string; could alternatively use Date type with transforms at runtime
updatedAt?: string; // optional last updated date
tags?: string[]; // optional tags array
}
/**
* Specific item types could be discriminated unions
*/
// An item representing a product
interface Product extends BaseItem {
type: "product";
name: string;
price: number;
currency: string; // ISO currency code, e.g., "USD", "EUR"
dimensions?: {
width: number;
height: number;
depth?: number | null;
};
inStock: boolean;
variants?: Product[]; // recursive structure for product variants (e.g., colors, sizes)
}
// An item representing a service
interface Service extends BaseItem {
type: "service";
name: string;
durationMinutes?: number | null; // optional duration
provider: User;
price?: number; // price could be optional for free services
metadata?: Record<string, ScalarOrArray<Scalar>>; // flexible metadata field
}
// An item which can be either a Product or a Service
type Item = Product | Service;
/**
* A collection that holds multiple items and has pagination information
*/
interface ItemCollection {
items: Item[];
totalCount: number; // total number of items in all pages
page: number; // current page number, 1-based indexing
pageSize: number; // items per page
nextPageToken?: string; // opaque token for fetching the next page, optional if last page
}
/**
* A top-level response object wrapping data with possible errors
*/
interface ApiResponse<T> {
data: T;
errors?: Array<{
code: string;
message: string;
details?: Record<string, unknown>;
}>;
metadata?: {
requestId: string;
timestamp: string; // ISO date string of the response
};
}
/**
* Example: Typing the API response returning a collection of items
*/
type ItemsApiResponse = ApiResponse<ItemCollection>;
```
---
### Explanation and Edge Cases Considered:
1. **Scalars and Nullable Fields:**
- Used `string | null` or `field?: Type | null` to represent optional or nullable fields, accommodating missing or explicitly `null` values.
2. **Arrays:**
- Arrays are handled explicitly (`string[]`, `Item[]`, etc.). Also demonstrated a generic union type `ScalarOrArray<T>` that accepts either a scalar or an array.
3. **Nested Objects:**
- Created nested interfaces like `Address` and dimension objects. Optional and nullable nested properties are demonstrated.
4. **Discriminated Unions:**
- `Item` is a union of `Product` and `Service`, discriminated by a `type` property, enabling safe type narrowing.
5. **Recursive Types:**
- `Product.variants` is an array of `Product`, allowing arbitrary nesting for product variants.
6. **Generics for API Responses:**
- `ApiResponse<T>` models a general API response wrapping any kind of data with optional error and metadata fields.
7. **Flexible Metadata:**
- Used `Record<string, unknown>` and `Record<string, ScalarOrArray<Scalar>>` for extensible key-value metadata fields.
8. **Id Types:**
- `id` fields allow both `string` and `number`, common in real-world JSON APIs.
9. **Date and Time:**
- Dates are string types (`ISO 8601`), assuming conversion happens elsewhere.
---
This design provides a solid scaffold for modeling quite complex nested JSON objects with attention to precision and real-world edge cases. Feel free to extend or specialize these interfaces to suit your specific data needs.How to adapt it
- •Paste real sample JSON; inferred types beat guessed ones.
- •Say how strict you want it: exact literals vs widened primitives.
Have your own rough prompt? Enhance it into a structured prompt like this in one click.
Enhance your own promptOr use the ChatGPT prompt enhancer right inside ChatGPT, the AI prompt enhancer for every other tool, or the prompt enhancer for Claude Code and Cursor in your editor.
More coding prompts
Code Translation Prompt That Preserves Behavior
A structured prompt that ports code between languages idiomatically, flagging behavior differences — with a real example translation.
Coding Interview Prompt for Real Practice
A structured prompt that runs mock interview drills: problem, hints on request, then review of your solution — with a real example session.
Cron Job Prompt That Gets the Schedule Right
A structured prompt that converts plain-English schedules into correct cron expressions with timezone caveats — with a real example.
Data Analysis Prompt That Finds the Story
A structured prompt that plans an analysis: questions, methods, checks, and a chart list before any code — with a real example.
Docker Compose Prompt for Multi-Service Stacks
A structured prompt that writes a compose file with services, networks, volumes, and healthchecks — with a real example file.
Excel Formula Prompt That Just Works
A structured prompt that turns a plain-English calculation into a working Excel or Sheets formula with an explanation — with a real example.