javascript - 函数的打字稿参数作为接口或类型
问题描述
是否可以在接口中使用函数定义的参数作为类型
(成类型或接口的数组?)
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`)
解决方案
该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]>
) {}
推荐阅读
- sql - SSMS 18 的列名无效问题
- html - 使用 Bulma 制作的视图布局未按预期显示在手机上
- laravel - Laravel 8 在插入数据库期间显示数组到字符串的转换
- python - “pip install models”失败,错误代码 1“No module named 'base'
- c++ - 隐式重载比较运算符
- filter - 从 Cassandra 表中获取示例数据
- php - Doctrine 无法从请求信息中获取实例
- autodesk-viewer - 使用 Forge Viewer 时 401 Unauthorized,但使用 CURL 它返回 200 OK
- python - 我使用 DLIBS 编写了一个人脸检测程序,但每次运行它都会出现此错误
- mysql - InterfaceError:执行操作失败;无法处理参数