有没有办法在TypeScrip中强制使用动态键?
我正在try 实现一种类型,该类型强制对象具有创建键和更新键,但这些键应该以域文本为前缀:
const productRepoA: Repo = { } // Should fail because create and update keys are missing
const productRepoB: Repo = { productCreate: () => null } // Should fail because update key is missing
const productRepoC: Repo = { productUpdate: () => null } // Should fail because update key is missing
const productRepoD: Repo = { productCreate: () => null, productUpdate: () => null } // Should work because both keys are provided
const orderRepoA: Repo = { } // Should fail because create and update keys are missing
const orderRepoB: Repo = { orderCreate: () => null } // Should fail because update key is missing
const orderRepoC: Repo = { orderUpdate: () => null } // Should fail because update key is missing
const orderRepoD: Repo = { orderCreate: () => null, orderUpdate: () => null } // Should work because both methods are provided
我想像这样的事情应该行得通:
type Repo = {
[key: `${string}Create`]: () => null
} & {
[key: `${string}Update`]: () => null
}
但遗憾的是,这允许像我的示例中的选项A、B和C那样缺少键