I have the following typescript type:
export class Status {
static readonly DONE = new Status('DONE', 'p-tag-green');
static readonly PENDING = new Status('PENDING', 'p-tag-yellow');
private constructor(
private _value: string,
private _class: string
) { }
}
and it is used in
export interface Reminder {
id: string;
status: Status;
}
When I make my httpClient request the JSON {"id": 5, "status": "DONE"} is returned, so the status field of the parsed Reminder object has the string value of DONE but it is not actually an object of type Status, thus I cannot retrieve the value property of the Status object.
I can get a Status object, if I manually map the response like so:
return this.httpClient.get(`api/v1/reminders/${id}`).pipe(
map((data: any) => ({
...data,
status: Reminder.Status[data['status'] as keyof typeof Reminder.Status]
}))
);
However, since I have a lot of cases like this one, is it somehow possible, to make this more generic, so that any interface like Reminder which includes any such pseudo-enum type like Status? I was thinking about http client interceptors or decorators, but couldn't make any of them work.
- Decorators because I'd need to make the
interfaceaclasswhich implies more changes I don't like - Http client interceptor because I don't have the types of the interface/classes that I need to parse to. However, maybe there is some clever prototype inspection that can be done?
DONE|PENDING, and I'd like to associate these values with extra information in a compile-time check. Thus, anytime a new status is added, the compiler forces me to choose tag color.