Trying to define the signature for a function that can be called with either 1 or 2 arguments, encountering an error stating that the type of the function with 2 arguments is not compatible with the defined type.
The specified type:
type Response = {
status: string;
result: object;
}
export interface CallbackFunction {
(response: Response): void;
(error: Error | null, response?: Response): void;
}
// Example code triggering 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 in use invokes this function with a single argument if the timeout option is not explicitly set, and with two arguments if the timeout occurs - first being an error on timeout (or null), and second being the result.
Though not an ideal design, unable to modify as it's part of a third-party library.