如何在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
相关产品推荐
相关产品推荐

