'Unable to index typescript object
This is what I have:
export const ID1 = "id1";
export const ID2 = "id2";
export const ID3 = "id3";
export const MAPPING1 = "MAPPING1";
export const MAPPING2 = "MAPPING2";
export const MAPPING3 = "MAPPING3";
export const MAPPINGS = {
ID1: MAPPING1,
ID2: MAPPING2,
ID3: MAPPING3
};
const finalMapping = MAPPINGS[key as keyof typeof MAPPINGS] || "NOTFOUND"
where key is a string. I've printed out test values like so:
console.log("key = " + key + " with type: " + (typeof key));
// prints this: key = ID1 with type: string
But finalMapping ends up always being NOTFOUND for me. Why am I unable to index the MAPPINGS object properly?
Solution 1:[1]
Not sure why this works, but it does:
export const MAPPINGS = {
ID1: MAPPING1,
ID2: MAPPING2,
ID3: MAPPING3
};
to
export const MAPPINGS = {
[ID1]: MAPPING1,
[ID2]: MAPPING2,
[ID3]: MAPPING3
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | stackoverflowflowflwofjlw |
