如何在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
相关产品推荐
相关产品推荐

