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

如何通过深度类型推断避免冗余泛型,自动关联schema与values类型?

避免长类型链泛型,自动约束values类型的解决方案

不用为TranslationConfigs或函数的每个键单独定义泛型,靠TypeScript的自动推导就能实现根据schema约束values的类型,还能保留自动补全能力。

完整代码实现:

const IntegrationSchemas = {
  URI: ['uri'],
  URI_STORE: ['uri', 'storeId'],
} as const;

type IntegrationSchemaKeys = keyof typeof IntegrationSchemas;

// 保留原泛型类型,用来关联schema和对应的values字段
type TranslationConfig<K extends IntegrationSchemaKeys> = {
  schema: K;
  values?: Record<(typeof IntegrationSchemas)[K][number], string | number | boolean>;
};

// TranslationConfigs不用加泛型,每个属性是所有可能的TranslationConfig联合类型
type TranslationConfigs = {
  points?: TranslationConfig<IntegrationSchemaKeys>;
  controls?: TranslationConfig<IntegrationSchemaKeys>;
};

// 给函数加泛型T,让TS自动推导传入的配置具体类型
const getTranslation = <T extends TranslationConfigs>(configs?: T) => {
  // 这里写你的函数逻辑
};

// 调用时自动补全schema和对应values,完全不用手动指定泛型
getTranslation({
  points: {
    schema: 'URI',
    values: {
      uri: 'some_uri', // 只会提示uri,不会出现storeId
    },
  },
  controls: {
    schema: 'URI_STORE',
    values: {
      uri: 'some_uri',
      storeId: 'some_store_id', // 自动提示这两个字段
    },
  },
});

原理说明

  • TranslationConfigs不再需要泛型,每个属性是所有TranslationConfig的联合,覆盖所有可能的schema类型;
  • 函数的泛型<T extends TranslationConfigs>会让TS自动识别传入的对象字面量:当你指定schema: 'URI'时,TS会自动把这个配置项的类型窄化为TranslationConfig<'URI'>,自然就约束了values只能包含uri字段;
  • 后续要加新的配置项(比如buttons?: ...),直接在TranslationConfigs里加就行,不用改泛型,扩展性拉满。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 06:37:03