I want to define an object that holds a pair of event handler name and event handler using React and TypeScript so I can pass around an array of objects like
{
eventHandlerName: 'onBlur',
eventHandler: (e: React.FocusEvent<HTMLInputElement>) => { /* something */},
}
I've tried defining this type as
type SpecifiedEventHandler<I, E extends keyof React.DOMAttributes<I>> = {
eventHandlerName: E,
handlerFunction: React.DOMAttributes<I>[E];
};
So as to call it like
const myObject: SpecifiedEventHandler<HTMLInputElement, keyof React.DOMAttributes<HTMLInputElement>>[] = {
[
{
eventHandlerName: 'onBlur',
handlerFunction: (e: React.FocusEvent<HTMLInputElement>) => { /* something */},
},
/* more here */
]
};
But the problem is that this is not restrictive enough. I can pass 'foobar'
as the handlerFunction
and it compiles just fine.
What am I missing here? The key is that I want the handlerFunction
to have the type of the field in React.DOMAttributes<HTMLInputElement>
that corresponds by name to the eventHandlerName
.
Thanks!