My workplace is currently dealing with some code that resembles the following:
interface Command {
action: string
}
interface Notification {
event: string
}
type Message = Command | Notification;
function func(type: string, callback: (msg: Message) => void) {
// ...
}
func("command", (c: Command) => console.log(c.action) )
The type error related to the second argument of the function call at the end shows:
Argument of type '(c: Command) => void' is not assignable to parameter of type '(msg: Message) => void'.
Types of parameters 'c' and 'msg' are incompatible.
Type 'Message' is not assignable to type 'Command'.
Property 'action' is missing in type 'Notification' but required in type 'Command'.ts(2345)
(It seems like the third line conflicts with the first.) Despite this error, I am certain that the callback argument will always be a Command. Is there a way to assert this and eliminate the error?