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

TypeScript中如何使接口内属性依赖同接口中另一个Record属性的键?

让TypeScript接口中foo属性仅为同接口bar的键组成的数组

你之前的代码无效,核心原因是Test["bar"]被定义为Record<string, string>,它的keyof结果是string类型,所以foo本质上允许任意字符串数组,自然不会对"dummy"这类无效值报错。

要实现需求且不需要手动指定泛型参数,完全可行,下面是两种方案:

方案一:使用satisfies关键字(TypeScript 4.9+)

利用satisfies让TypeScript自动推断bar的键类型,同时校验foo的合法性:

type Test<T extends string> = {
  bar: Record<T, string>;
  foo: T[];
};

// 自动推断bar的键为"hello",foo只能包含该值
const test = {
  bar: { hello: "world" },
  foo: ["hello"]
} satisfies Test<string>;

// 以下代码会报错,符合预期
const invalidTest = {
  bar: { hello: "world" },
  foo: ["dummy", "hello"]
} satisfies Test<string>;

方案二:泛型工厂函数(兼容旧版本)

通过函数参数的类型推断,自动推导bar的键类型,无需手动指定泛型:

function createTest<T extends string>(config: {
  bar: Record<T, string>;
  foo: T[];
}) {
  return config;
}

// 正常通过,自动推断T为"hello"
const validTest = createTest({
  bar: { hello: "world" },
  foo: ["hello"]
});

// 触发错误,"dummy"不在bar的键中
const invalidTest = createTest({
  bar: { hello: "world" },
  foo: ["dummy"]
});

这两种方式都不需要手动写Test<"hello">这类指定泛型的代码,TypeScript会自动完成类型推断和校验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 06:45:02