Check out my TS playground here
// I have colours
const colors = {
Red: "Red",
Blue: "Blue",
Green: "Green"
}
type TColor = keyof typeof colors;
// Some colours have moods associated with them
const colorsToMood = {
Red: "Hunger",
Blue: "Calm"
}
type TPayload = {
color: TColor,
}
// myColor comes from a payload, and really could be either Red, Blue, or Green
const myPayload: TPayload = { color: "Blue" }
let myColor: TColor = myPayload.color;
// Why can't I just use it to index? Intuitively the result is either string if the key exists or undefined if it doesn't, it doesn't need to be implicitly "any"
const resultingMood = colorsToMood[myColor];
// I'm not interested in casting myColor to keyof typeof colorsToMood, since I expect that it could also be "Green" (which is handled!)
if (resultingMood) {
console.log("Here's the mood!", colorsToMood[myColor]);
} else {
console.log("That colour doesn't have a mood");
}
This scenario puzzles me as there seems to be an error even though the return type should be determinable, especially when accessing a non-existent key in an object.
All other solutions I've come across involve forced type conversions, which in this case would provide inaccurate information about the actual type.
How would you recommend resolving this issue?