函数的Typescript参数作为接口或类型 [英] Typescript argument of function as interface or type

查看:241
本文介绍了函数的Typescript参数作为接口或类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

参数 type以元组形式返回函数的参数。

The Parameters type returns the arguments of a function as a tuple.

type A = Parameters<(a: string, b: number) => void> // [string, number]

可以键入 args 参数为:

function fireMiddleware<EventName extends keyof MiddlewareEvent>(
    eventId: keyof MiddlewareEvent,
    args: Parameters<MiddlewareEvent[EventName]>
) {}

游乐场

这篇关于函数的Typescript参数作为接口或类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆