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

如何抽象TypeScript联合类型以实现多位置复用与统一维护?

如何在TypeScript中抽象并复用联合类型

你想要实现的复用思路完全正确,只差一步小小的调整就可以搞定啦!下面就一步步教你怎么把重复的联合类型抽出来,实现单一维护、多处复用:

1. 先定义可复用的联合类型

首先把你重复写的"default" | "template1" | "template2"抽成一个独立的type,建议用更语义化的名字(比如TemplateName),避免和变量名混淆,把它放在所有需要引用它的代码前面:

// 抽出来的全局复用联合类型
type TemplateName = "default" | "template1" | "template2";

2. 在需要的地方直接引用这个类型

不管是函数的参数类型,还是接口的属性类型,直接用这个类型名代替原来的重复代码就行:

function useTemplate(templateName: TemplateName) {
  var template = templates.find(t => t.name === templateName);
  return { template, columns: template?.grid?.columns }
}

function useTemplateData(templateName: TemplateName) {
  return [];
}

interface TableProps {
  templateName: TemplateName;
}

这样以后要新增或修改模板名称,只需要修改TemplateName这一处,所有引用它的地方都会自动同步,完美实现统一维护!

额外进阶技巧:动态推导联合类型

如果你的模板列表是从一个数组/对象里来的(比如你已经有一个templates数组存着所有模板数据),还可以让TypeScript自动帮你推导联合类型,连手动写"default" | "template1" | "template2"都省了:

// 用as const让TypeScript推导最精确的字面量类型
const templates = [
  { name: "default", grid: { columns: 3 } },
  { name: "template1", grid: { columns: 4 } },
  { name: "template2", grid: { columns: 5 } }
] as const;

// 自动从数组元素的name属性推导联合类型
type TemplateName = typeof templates[number]["name"];
// 此时TemplateName自动等于 "default" | "template1" | "template2"

以后新增模板的时候,只需要往templates数组里加数据,TemplateName会自动更新,彻底告别手动维护联合类型的麻烦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 02:44:07