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

如何在TypeScript中强制要求带前缀的动态键?

TypeScript强制要求带领域前缀的动态键实现方案

你需要约束对象必须包含同一领域前缀的Create和Update键,原写法无法生效的原因是:字符串模板索引签名([key: ${string}Create])仅规定「符合格式的键必须满足类型」,但不强制要求对象必须存在这类键——空对象或仅含单个键的对象都不会触发报错。

正确实现方式:泛型+模板字符串类型

通过泛型接收领域前缀,直接定义两个必选的具体键,TypeScript会强制要求对象必须包含这两个键:

// 定义泛型Repo类型,T为领域前缀(如'product'、'order')
type Repo<T extends string> = {
  [K in `${T}Create` | `${T}Update`]: () => null;
};

使用示例

// 符合要求的情况
const productRepoD: Repo<'product'> = { productCreate: () => null, productUpdate: () => null };
const orderRepoD: Repo<'order'> = { orderCreate: () => null, orderUpdate: () => null };

// 以下情况均会触发TypeScript报错,符合预期
const productRepoA: Repo<'product'> = { }; // 缺少productCreate和productUpdate
const productRepoB: Repo<'product'> = { productCreate: () => null }; // 缺少productUpdate
const productRepoC: Repo<'product'> = { productUpdate: () => null }; // 缺少productCreate

const orderRepoA: Repo<'order'> = { }; // 缺少orderCreate和orderUpdate
const orderRepoB: Repo<'order'> = { orderCreate: () => null }; // 缺少orderUpdate
const orderRepoC: Repo<'order'> = { orderUpdate: () => null }; // 缺少orderCreate

优化:自动推断前缀(无需手动指定)

如果不想每次显式写前缀,可以用辅助函数让TypeScript自动推断:

function createRepo<T extends string>(repo: Repo<T>): Repo<T> {
  return repo;
}

// 自动推断前缀为'product',无需手动指定
const productRepo = createRepo({
  productCreate: () => null,
  productUpdate: () => null
});

// 报错:缺少productUpdate键
const badProductRepo = createRepo({
  productCreate: () => null
});

内容的提问来源于stack exchange,提问作者Giovanii Mirko Terrazas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 02:12:38