My challenge involves an object with typed keys referred to as Statuses (StatusesType
). The task is to iterate over the object and pass keys to a method that expects parameters of the same type, let's call it statusPrinter()
.
type StatusesType = 'PENDING' | 'APPROVED' | 'REJECTED';
type SomeMap = {
[key in StatusesType]?: number
}
const STATUSES: SomeMap = {
PENDING: 5,
REJECTED: 2,
};
function statusPrinter(val: StatusesType) {
console.log('- ', val);
}
Object.keys(STATUSES).forEach(status => {
statusPrinter(status);
});
However, TypeScript throws an error when I use statusPrinter(status);
, stating:
error TS2345: Argument of type 'string' is not assignable to parameter of type 'StatusesType'.
The question now becomes how can I pass this key while preserving its original type?
I am aware of the workaround using
statusPrinter(<StatusesType>status);
, but I would prefer a more native solution if possible.
Update: If maintaining type consistency during iteration over object keys using Object.keys()
proves impossible, what other alternatives exist? Is there a way to iterate over keys while preserving types, and if so, which approach is recommended? While I am open to options beyond Object.keys()
, preserving the original object structure is ideal.
Thank you!