I have an interface:
interface HandlerEvent<T = void> {
data: T // I would like to keep this as a required parameter
}
I would like to be able to make data
required if I pass a value when calling it, else make it optional.
const actionHandler = ({}: HandlerEvent):void => { }
actionHandler({}) // Fails as data is required. How to get rid of error without specifying data?
actionHandler({data: undefined }) // A bit silly imo
So that when no parameters are provided to the generic I can call the function without it asking for data
and if I do provide T
then it will require it. I can of course do data?: T
but I'd like to find an alternative to checking the presence of data
in code. I thought the default parameter (void
in this case) would work but it still requires me to pass data
.
Right now I cannot call: actionHandler()
without errors even when I do not need data. Perhaps I am overlooking what to pass to the generic?
I've found a few related discussions but I don't see a solution - they just are closed though perhaps I missed it deep 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
And How to pass optional parameters while omitting some other optional parameters?
I did find a post that wraps the generic - is there a simpler way that I am overlooking?
TS Playground link