When working with an interface, I have the following:
interface HandlerEvent<T = void> {
data: T // This parameter should always be required
}
I want to make data
a required field if a value is passed when calling the function, otherwise it should be optional.
const actionHandler = ({}: HandlerEvent):void => { }
actionHandler({}) // Fails because data is required. How can I eliminate this error without specifying data?
actionHandler({data: undefined }) // Seems unnecessary in my opinion
So, I aim to be able to call the function without providing parameters for the generic, without being prompted for data
. However, if I do provide a value for T
, then data
should be mandatory. While I could use data?: T
, I am looking for an alternative to manually checking the presence of data
in the code. I initially thought that setting the default parameter (void
in this case) might resolve the issue, but it still requires me to pass data
.
Currently, I receive errors even when trying to call actionHandler()
without needing data. Is there something I'm missing about passing arguments to the generic?
I've come across several discussions on this topic, but couldn't find a definitive solution - they seem to have been closed without a clear answer, unless I missed it buried in the comments.
- https://github.com/Microsoft/TypeScript/issues/2175
- https://github.com/Microsoft/TypeScript/issues/209
- https://github.com/microsoft/TypeScript/issues/2175
- https://github.com/Microsoft/TypeScript/issues/467
Referencing How to pass optional parameters while omitting some other optional parameters?
I did discover a related article that involves wrapping the generic - but is there a simpler approach that I may have overlooked?
Play around with TypeScript in this TS Playground link