I'm trying to define the signature for a function that might be called with 1 or 2 arguments, but I'm getting an error that the type of the function with 2 arguments is not assignable to my defined type.
The type that I defined:
type Response = {
status: string;
result: object;
}
export interface CallbackFunction {
(response: Response): void;
(error: Error | null, response?: Response): void;
}
// Example code to get the error
// OK
// res: Response | Error | null
export const fn: CallbackFunction = (res) => {
// ...
};
// Error
// Type '(err: Error | null, res: Response | undefined) => void' is not assignable to type 'CallbackFunction'.
export const fn2: CallbackFunction = (err, res) => {
// ...
};
// Error
// Argument of type '{ status: string; result: {}; }' is not assignable to parameter of type 'Error'
fn({ status: 'Test', result: {} })
The library that I'm using calls this function with only 1 argument if I'm not explicitly using the timeout option, otherwise it calls it with 2 arguments, the first will be an error on timeout or null otherwise with the second argument being the result.
I know this is not the best design, but I can't change the code, it's a third party library.