CodexBloom - Programming Q&A Platform

How to Type a Callback Function with Optional Parameters in TypeScript?

πŸ‘€ Views: 2 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-11
typescript react callback

I'm getting frustrated with I've looked through the documentation and I'm still confused about I'm currently working on a React project using TypeScript 4.5, and I'm working with scenarios typing a callback function that has optional parameters... I want to create a higher-order function that accepts another function as a parameter, which may or may not have additional arguments. Here’s what I have so far: ```typescript type Callback<T> = (data: T, extraInfo?: string) => void; function withCallback<T>(callback: Callback<T>) { const data: T = fetchData(); // Assume fetchData returns data of type T callback(data); } ``` However, when I try to call `withCallback` like this: ```typescript withCallback((data) => { console.log(data); }); ``` I get a TypeScript behavior: `Argument of type '(data: T) => void' is not assignable to parameter of type 'Callback<T>'`. It seems like TypeScript is not recognizing that the second parameter in `Callback<T>` is optional, and I need to figure out how to resolve this. I’ve also tried defining the callback like this: ```typescript const myCallback: Callback<MyType> = (data, extraInfo) => { console.log(data); }; ``` But I still run into issues when I try to pass `myCallback` into `withCallback()`. How can I make TypeScript understand that the second parameter is optional and allow the callback to be used without it? Any advice or best practices on handling this would be greatly appreciated! This is part of a larger application I'm building. This is my first time working with Typescript latest. Is this even possible?