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

TypeScript中能否将字符串字面量联合类型存入interface?

把字符串联合类型整合到Interface的正确方法

你原来的写法不符合TypeScript语法规则,因为interface是用来定义对象结构的,不能直接把字符串联合类型写在大括号里。要实现把这个联合类型和interface结合的需求,有两种常用方式:

方式1:直接在interface属性中定义联合类型

如果不需要单独复用这个联合类型,可以直接将它作为interface内某个属性的类型:

interface FilterConfig {
  filterType: "Filter1" | "Filter2" | "Filter3" | "Filter4" | "Filter5";
}

// 使用示例
let myFilter: FilterConfig = {
  filterType: "Filter1"
};

方式2:先定义联合类型,再在interface中引用

如果这个联合类型需要在多个地方复用,先单独用type定义,再在interface里引用它:

type FilterType = "Filter1" | "Filter2" | "Filter3" | "Filter4" | "Filter5";

interface FilterConfig {
  filter: FilterType;
}

// 使用示例
let myFilter: FilterConfig = {
  filter: "Filter1"
};

如果你的需求是让interface本身等价于这个字符串联合类型,那是做不到的——interface只能描述对象的形状,无法直接表示字符串字面量的联合类型,这种场景下用type定义联合类型才是正确选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 05:40:24