TypeScript中如何对回调函数参数进行类型断言以消除类型不兼容错误?
First, let's break down why you're seeing this error: TypeScript can't infer the relationship between the "command" string you're passing as the first argument and the type of message the callback will receive. Right now, your func accepts any string as the first parameter and a callback that handles any Message (either Command or Notification). So TypeScript is correctly warning you that the callback you provided (which only handles Command) might receive a Notification later on.
Solution 1: Use a Type Assertion (Quick Fix)
If you're absolutely certain that when you pass "command" the callback will only ever get a Command, you can use a type assertion inside the callback to tell TypeScript to treat the incoming message as a Command:
func("command", (msg: Message) => console.log((msg as Command).action));
Alternatively, you can assert the callback type itself when passing it to func (though this is less safe, as it bypasses more type checking):
func("command", ((c: Command) => console.log(c.action)) as (msg: Message) => void);
Solution 2: Make func Generic (Type-Safe Approach)
A better long-term fix is to refactor func to be generic, so TypeScript can link the first argument's string type to the expected message type in the callback. This eliminates the need for assertions entirely while keeping type safety:
First, create a type map that associates each message type string with its corresponding interface:
type MessageTypeMap = { command: Command; notification: Notification; };
Then update func to use this map:
function func<T extends keyof MessageTypeMap>(type: T, callback: (msg: MessageTypeMap[T]) => void) { // Your implementation here—just ensure you only pass MessageTypeMap[T] to the callback }
Now when you call func with "command", TypeScript automatically knows the callback expects a Command, so your original call will work without any errors:
func("command", (c: Command) => console.log(c.action)); // No type error!
About the "Opposite" Error Message Line
The error message might seem contradictory at first, but it's explaining the root issue clearly:
- The callback you provided expects a
Command, butfuncexpects a callback that can handle anyMessage. - This means when
functries to pass aMessage(which could be aNotification) to your callback, thatMessageisn't assignable toCommand(sinceNotificationlacks theactionproperty).
So the lines are just two sides of the same coin: the callback's parameter type is incompatible because it can't accept all possible Message values.
内容的提问来源于stack exchange,提问作者Vlad Mashkautsan

