作为接口或类型的函数的Typescript参数

问题描述 投票:0回答:1

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

(放入类型或接口数组?)

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`)
javascript typescript callback
1个回答
0
投票

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

Playground

© www.soinside.com 2019 - 2024. All rights reserved.