是否可以在接口中将函数定义的参数用作类型
(放入类型或接口数组?)
export interface MiddlewareEvent {
onNewAccount: (accountId: string, timestamp: number) => void,
onAccountDelete: (accountId:string, timestamp:number)=>void,
}
const middlewareMap: Map<keyof MiddlewareEvent,((...arg: any) => void )[]> = new Map();
function fireMiddleware<EventName extends keyof MiddlewareEvent>(
eventId: EventName,
args: any[]
) {
const middleware = middlewareMap.get(eventId);
if (middleware?.length) {
middleware.forEach((m) => {
m(...args);
});
}
}
fireMiddleware(`onNewAccount`, [123, `2020-05-21T21:42:00.496Z`])
console.log(`Wait, Typescript should have prevented this`)
console.log(`account Id is string not number`)
console.log(`datetime has been changed to timestamp and is now a number`)
Parameters
类型以元组形式返回函数的参数。
type A = Parameters<(a: string, b: number) => void> // [string, number]
使用args
参数可以输入:
function fireMiddleware<EventName extends keyof MiddlewareEvent>(
eventId: keyof MiddlewareEvent,
args: Parameters<MiddlewareEvent[EventName]>
) {}