Is there a way to ensure specific keys in objects using TypeScript?
I am attempting to define a type that mandates objects to have keys prefixed with a specific domain text, such as 'create' and 'update':
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
I initially thought that this approach would suffice:
type Repo = {
[key: `${string}Create`]: () => null
} & {
[key: `${string}Update`]: () => null
}
However, this implementation allows missing keys like in examples A, B, and C