When my backend sends a JSON object with id strings mapping to data, I make use of the Typescript type Record
. Since some ids may not exist, I define it as:
let data: Record<string, number | undefined> = {
'asdf': 1
};
To process this data and check if a key exists, I do:
const id = 'asdf';
if (id in data) {
const id_data = data[id];
console.log(id_data + 1); // compiler warns it might be undefined
}
The compiler provides better support for other patterns. So, I'm unsure if this is the best way to handle my backend response. Any suggestions?