Below is a simplified version of the code I am working with, showcasing a type that can be an interface or another:
interface ChatBase {
roomId?: string
type: "message" | "emoji"
configs: unknown
}
interface ChatMessage extends ChatBase {
type: "message",
configs:{
text?: string
}
}
interface ChatEmoji extends ChatBase {
type: "emoji",
configs: {
emoji?: string
}
}
type Chat = ChatMessage | ChatEmoji
You can also explore this on the typescript playground
In my actual code, trying to check if "emoji" is defined in configs
has become overly complicated. Is there a simpler way?
const chats: Chat[] = [
{ type: "message", configs: { text: "string" } },
{ type: "emoji", configs: { emoji: "string" } }
]
chats.map(chat=>{
if(chat.configs.emoji){ // <=== THROWS ERROR SHOWN BELOW
console.log("Has an emoji")
}
if("emoji" in chat.configs && chat.configs.emoji){ // <= Works but ridiculously long
console.log("Has an emoji")
}
if(chat.type === "emoji" && chat.configs.emoji){ // <= Works but sometimes I test for shared properties
console.log("Has en emoji")
}
})
However, TypeScript is giving me an error:
Property 'emoji' does not exist on type '{ text?: string | undefined; }'.
The question now is, how can I simplify
if("emoji" in chat.configs && chat.configs.emoji)
without it being excessively lengthy?