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

如何定义TypeScript接口使字段为同接口数组的成员?

TypeScript:自动约束接口字段为同接口数组的成员

你遇到的核心问题是:直接使用泛型接口时,若不显式指定泛型参数,TypeScript会自动扩展泛型范围以匹配所有字段,导致defaultFruit可以是任意字符串。要实现自动推导且无需重复编写类型,推荐用泛型函数来辅助类型推断,而不是直接使用接口声明变量。

解决方案:泛型工厂函数

通过定义一个泛型函数,让TypeScript自动从fruits数组推导出元素类型,再约束defaultFruit必须属于该类型:

function createExample<F extends string>(props: {
  fruits: ReadonlyArray<F>;
  defaultFruit: F;
}) {
  return props;
}

// 合法赋值:正常通过
const validExample = createExample({
  fruits: ["Apple", "Banana"],
  defaultFruit: "Apple"
});

// 非法赋值:TypeScript会报错("Something Else"不属于"Apple"|"Banana")
const invalidExample = createExample({
  fruits: ["Apple", "Banana"],
  defaultFruit: "Something Else"
});

原理说明

  • 泛型函数createExample会自动从传入的fruits数组中推断出元素类型F(这里是"Apple" | "Banana")。
  • 函数参数的类型约束会强制defaultFruit必须是F的成员,无需手动指定泛型参数。

结合接口的写法

如果你希望保留接口定义,可以将接口与泛型函数结合:

interface Example<F extends string> {
  fruits: ReadonlyArray<F>;
  defaultFruit: F;
}

function createExample<F extends string>(props: Example<F>): Example<F> {
  return props;
}

// 使用方式和上面一致
const e = createExample({
  fruits: ["Apple", "Banana"],
  defaultFruit: "Banana"
});

这种方式既保留了接口的类型定义,又借助泛型函数实现了自动类型推导,避免了重复编写泛型参数的麻烦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:25:51