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

如何在TypeScript类型内部创建临时类型以实现DRY?

解决方案

兼容所有TypeScript版本的写法

可以通过给泛型添加带默认值的参数实现内部临时类型定义,既避免重复书写,又不用把类型暴露到外部:

type FetchOptions<T, K = string & keyof T> = {
  explode?: K | K[];
};

泛型参数K会自动推导为string & keyof T,使用时无需手动传递,和你原本的调用方式完全一致。

TypeScript 5.4+ 专属写法

如果你的TypeScript版本在5.4及以上,还可以用更直观的where子句定义内部临时类型:

type FetchOptions<T> = {
  explode?: K | K[];
} where K = string & keyof T;

验证示例

用你提供的代码测试,两种写法都能正常工作:

class ProductVariant {}

class Product {
  id: number | string;
  name: string;
  variants?: ProductVariant[];
  attributes?: ProductVariant[];
}

const fetchProducts = (options: FetchOptions<Product> = {}) => {
  // ...
};

fetchProducts({ explode: 'variants' });
fetchProducts({ explode: ['variants', 'attributes'] });

内容的提问来源于stack exchange,提问作者gremo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:06:49