首页 > 解决方案 > 函数的打字稿参数作为接口或类型

问题描述

是否可以在接口中使用函数定义的参数作为类型

(成类型或接口的数组?)

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`)

标签: javascripttypescriptcallback

解决方案


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]>
) {}

操场


推荐阅读