I am currently working on creating a type-safe callback function in TypeScript with a Node.js style. My goal is to define the err
parameter as an Error
if it exists, or the data
parameter as T
if not.
- When I utilize the following code:
export interface SafeCallback<T> {
(err: unknown): void;
(err: undefined, data: T): void;
}
const subscribe = <T>(callback: SafeCallback<T>) => {
let result: T;
try {
// result = something
} catch (e) {
callback(e);
return;
}
callback(undefined, result);
};
subscribe<{id: string}>((err, data?) => {
if (!err) {
console.log(data.id);
}
});
The error message states that 'data' is of type 'unknown'.
- If I remove the question mark from the
data
, I receive the following error:Argument of type '(err: undefined, data: { id: string; }) => void' is not assignable to parameter of type 'SafeCallback<{ id: string; }>'
Even after attempting to define err: Error
in the first overload for both cases, the issue remains unresolved.
Are there any other approaches I should consider?
Thank you!