I can’t get this to work at all:
type Method = {
(pathname: string, handler: CallableFunction): void,
(pathname: string, middleware: CallableFunction[], handler: CallableFunction): void,
}
type Route = {
method: string,
pathname: string,
middleware?: CallableFunction[],
handler: CallableFunction,
}
const routes: Route[] = []
export const get: Method = (param1: string, param2: CallableFunction | CallableFunction[], param3?: CallableFunction) => {
push('GET', param1, param2, param3)
}
export const post: Method = (param1: string, param2: CallableFunction | CallableFunction[], param3?: CallableFunction) => {
push('POST', param1, param2, param3)
}
const push = (method: string, param1: string, param2: CallableFunction | CallableFunction[], param3?: CallableFunction) => {
routes.push({
method: method,
pathname: param1,
middleware: typeof param2 == CallableFunction[] ? param2 : undefined,
handler: typeof param2 == CallableFunction ? param2 : param3,
})
}
Errors:
Type ‘CallableFunction | CallableFunction[] | undefined’ is not assignable to type ‘CallableFunction[] | undefined’.
‘CallableFunction’ only refers to a type, but is being used as a value here.
How do I check if they are the exact type I am using? Or do I need to be less strict?
Also, is there a way to implement DRY principles so I don’t have to repeated the same thing for every route method? See get
, post
, etc.
I tried using typeof param2 == 'function'
but have no idea how to use it for an array of callable functions, etc.
Ideally I want to be able to check the exact types of the overloads…
kejedi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1