I have a 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");
}
It doesn't really make sense to me that this example should have an error when the return type is (I think) knowable, even though I'm using something to index an object that doesn't exist as a key.
All the other examples I've seen are contrived or involve casting types in order to solve it, but in this case that would be "lying" about what the type actually is.
What's the preferred way of handling this?