作为接口或类型的函数的 Typescript 参数
Typescript argument of function as interface or type
是否可以在接口中使用函数定义的参数作为类型
(转换为类型或接口的数组?)
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
类型 returns 函数的参数作为元组。
type A = Parameters<(a: string, b: number) => void> // [string, number]
使用它,您可以将 args
参数键入为:
function fireMiddleware<EventName extends keyof MiddlewareEvent>(
eventId: keyof MiddlewareEvent,
args: Parameters<MiddlewareEvent[EventName]>
) {}
是否可以在接口中使用函数定义的参数作为类型
(转换为类型或接口的数组?)
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
类型 returns 函数的参数作为元组。
type A = Parameters<(a: string, b: number) => void> // [string, number]
使用它,您可以将 args
参数键入为:
function fireMiddleware<EventName extends keyof MiddlewareEvent>(
eventId: keyof MiddlewareEvent,
args: Parameters<MiddlewareEvent[EventName]>
) {}