I receive some reference data in this form from my server:
interface Status {
id: number;
code: string;
description: string;
}
In JavaScript, I would convert it into something that I could reference in enum style by doing this:
let as = resp.data as Status[];
let statuses: any = {};
statuses.descriptions = {};
for (let a of as) {
statuses[a.code] = a.id;
statuses.descriptions[a.id] = a.description;
}
which would allow me to write:
statuses.ONE_STATUS
and I'd get back the id of the record. This made it easy to reference the records by their 'code' (ie. symbolically) rather than by assuming the ID of the record in the database when setting foreign keys, etc.
Now I'm converting this to TypeScript and can't figure out how to write this code and not use the any type for statuses.
Any suggestions?
--- Update ---
Seems I can't get exactly what I want, but I can do this:
interface Status {
id: number;
description: string;
}
interface Statuses {
[statusIndex: string]: Status;
}
which I can then populate with this:
let statuses: Statuses;
for (let a of as) {
statuses[a.code].id = a.id;
statuses[a.code].description = a.description;
}
and that doesn't do exactly what I want, but it does do:
statuses.ONE_STATUS.id or statuses["ONE_STATUS"].id
to get the id, and
statuses.ONE_STATUS.description
to get the description.
The dictionary approach is what I would have done in C#, so I feel right at home :)