我正在尝试在 TypeScript 上实现简单的事件调度程序。
我的自定义类型声明如下:
events.d.ts:
type AppEvent = { [key: string]: any }
type AppEventListener<T> = <T extends AppEvent>(event: T) => void;
Run Code Online (Sandbox Code Playgroud)
当我在这个函数中传递任何对象时
public addListener<T extends AppEvent>(event: T, listener: AppEventListener<T>)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Argument of type '(event: TestEvent) => void' is not assignable to parameter of type 'AppEventListener<typeof TestEvent>'.
Types of parameters 'event' and 'event' are incompatible.
Type 'T' is not assignable to type 'TestEvent'.
Property 'name' is missing in type 'AppEvent' but required in type 'TestEvent'.
Run Code Online (Sandbox Code Playgroud)
因此,该类型AppEvent不能具有任何附加属性。如何让它发挥作用?任何帮助表示赞赏。
完整代码示例: …