问题
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`)
回答1:
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]>
) {}
Playground
来源:https://stackoverflow.com/questions/61945580/typescript-argument-of-function-as-interface-or-type