如何在不保留示例对象的前提下生成其TypeScript类型?
Totally get this frustration—you want to leverage TypeScript’s ability to infer types from real-looking example data, but you don’t want that dummy object cluttering up your compiled JavaScript. Here are a couple of straightforward fixes:
Solution 1: Inline the Example in the Type Alias
Instead of declaring a separate runtime variable, stick your example object directly inside the typeof operator when defining your type. Since this is purely a type-level operation, TypeScript won’t emit any of this code to your final JS bundle:
type SuccessResponse = typeof ({ rates: [ { cost: 10, description: "10$ shipping" }, { cost: 20, description: "20$ shipping", guaranteedDaysToDelivery: 5 } ] } as const);
The as const modifier is important here—it tells TypeScript to infer the most specific types possible (like literal values for cost instead of a generic number, and exact string literals for description), which is probably what you want.
Solution 2: Move the Example to a Declaration File
If you prefer to keep your example data organized separately, pop it into a .d.ts file. Declaration files are never compiled to JavaScript, so your example stays purely a source for type inference:
- Create a file like
api-types.d.tsin your project:
const exampleResponse = { rates: [ { cost: 10, description: "10$ shipping" }, { cost: 20, description: "20$ shipping", guaranteedDaysToDelivery: 5 } ] } as const; export type SuccessResponse = typeof exampleResponse;
- Import the type into your main TypeScript files whenever you need it:
import type { SuccessResponse } from './api-types';
Either of these approaches will let you keep the inferred type without the extra runtime baggage. Pick whichever fits better with how you organize your code!
内容的提问来源于stack exchange,提问作者mikeysee

