Typescript argument of function as interface or type

↘锁芯ラ 提交于 2020-06-01 05:36:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!