TypeScript: How to properly type a function that accepts multiple callback signatures?
I'm stuck on something that should probably be simple. This might be a silly question, but I'm working on a project and hit a roadblock. I'm working on a utility function that needs to accept multiple callback signatures depending on the arguments provided. I want to ensure that TypeScript enforces correct types for the callbacks based on the input parameters. Here's what I've tried so far: ```typescript type CallbackWithoutArgs = () => void; type CallbackWithArgs<T> = (arg: T) => void; function handleCallbacks<T>(callback: CallbackWithoutArgs | CallbackWithArgs<T>): void { if (callback.length === 0) { // Call a callback without any args callback(); } else { // Create a test argument to pass const arg: T = getTestArgument(); callback(arg); } } function getTestArgument(): number { return 42; } handleCallbacks(() => console.log('No args callback')); // This works handleCallbacks((num: number) => console.log(num)); // This should work too ``` However, I'm working with a TypeScript behavior that says: ``` Argument of type 'CallbackWithoutArgs | CallbackWithArgs<T>' is not assignable to parameter of type 'CallbackWithArgs<T>'. ``` The scenario arises because TypeScript need to infer that `callback` is of the correct type when I call it with arguments. I tried using function overloads, but that just added more complexity without resolving the typing issues. Is there a better way to achieve this while keeping my types safe? I'm using TypeScript version 4.5.2. Any advice would be appreciated! I'm working on a desktop app that needs to handle this. Thanks for any help you can provide!