You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不保留示例对象的前提下生成其TypeScript类型?

Keep Type from Example Object Without Emitting It in 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:

  1. Create a file like api-types.d.ts in your project:
const exampleResponse = {
  rates: [
    { cost: 10, description: "10$ shipping" },
    { cost: 20, description: "20$ shipping", guaranteedDaysToDelivery: 5 }
  ]
} as const;

export type SuccessResponse = typeof exampleResponse;
  1. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:18:40