Imagine having an enum called status
export enum status {
PENDING = 'pending',
SUCCESS = 'success',
FAIL = 'fail'
}
This enum is used in multiple places and should not be easily replaced. However, other developers might add or remove statuses in the future.
Now, I want to create an object obj that looks like this:
let obj = {
pending: 10,
success: 20,
fail: 0
}
I want to define an interface for this object to only allow specific keys from the enum defined above.
interface objInterface = {
[key: string]: number;
}
The issue with this approach is that it allows any key to be set in obj, which is not desirable. I want to restrict it to only the values specified in the enum.
An attempt was made using the following code snippet:
type objType = {
[K in keyof typeof status]: number;
};
However, hovering over it reveals a translation to:
type objType = {
readOnly PENDING: number,
readOnly SUCCESS: number,
readOnly FAIL: number
}
This does not fully address the requirement. What would be the best way to achieve this restriction?