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

如何限制TypeScript类型中startWith字段仅为sequences的键(非泛型方案)

如何在非泛型场景下约束startWith为sequences的键?

首先,直接用keyof SomeType['sequences']无效的原因是:Record<string, unknown[]>的键类型是string,所以keyof的结果自然是string,无法起到精准约束作用。

如果不想显式使用泛型(避免每次都写SomeType<具体类型>),可以通过工厂函数自动推断类型的方式实现需求,无需手动指定泛型参数:

// 定义工厂函数,自动推断sequences的键类型T
function createSomeType<T extends string>(config: {
  sequences: Record<T, unknown[]>;
  startWith: T;
}) {
  return config;
}

// 使用示例:TypeScript会自动推断T为"foo"|"bar"
const validConfig = createSomeType({
  sequences: {
    foo: [1, 2],
    bar: ["a", "b"]
  },
  startWith: "foo" // ✅ 合法,只能是foo或bar
});

const invalidConfig = createSomeType({
  sequences: {
    foo: [1, 2]
  },
  startWith: "baz" // ❌ 报错:类型"baz"不能赋值给类型"foo"
});

这种方式的核心是利用函数的类型推断能力:当你传入具体的sequences对象时,TypeScript会自动提取它的键作为泛型T,并约束startWith必须是这些键之一,全程无需手动声明泛型参数,避免了冗余代码。

为什么非泛型类型本身无法实现?
TypeScript的非泛型类型是静态固定的,定义时无法动态关联两个字段的类型关系。只有通过泛型(或依赖泛型的工厂函数)才能在使用时根据具体值动态绑定类型约束。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 02:31:03