Is it possible to use the argument of a function definition in an interface as type
( into an array of type or interface? )
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`)
The Parameters
type returns the arguments of a function as a tuple.
type A = Parameters<(a: string, b: number) => void> // [string, number]
Using that you can type the args
argument as:
function fireMiddleware<EventName extends keyof MiddlewareEvent>(
eventId: keyof MiddlewareEvent,
args: Parameters<MiddlewareEvent[EventName]>
) {}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.