Last active
December 8, 2021 21:47
-
-
Save alii/ea37a47030bd536a68603ae56d156a07 to your computer and use it in GitHub Desktop.
An easy way to not have to remember React event handlers types in TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type RemoveOn<T extends string> = T extends `on${infer R}` ? R : T; | |
type PropsFor<El extends keyof JSX.IntrinsicElements> = JSX.IntrinsicElements[El]; | |
type OnProps<El extends keyof JSX.IntrinsicElements> = Uncapitalize<RemoveOn<Extract<keyof PropsFor<El>, `on${string}`>>>; | |
type HandlerFor<El extends keyof JSX.IntrinsicElements, Ev extends OnProps<El>> = NonNullable<PropsFor<El>[`on${Capitalize<Ev>}` & keyof PropsFor<El>]>; | |
// Creating with a callback | |
function handlerFor<El extends keyof JSX.IntrinsicElements, Ev extends OnProps<El>>(event: [El, Ev], handler: HandlerFor<El, Ev>) { | |
return handler; | |
} | |
const onChange = handlerFor(['input', 'change'], event => { | |
event.target.value; | |
event.target.focus(); | |
}); | |
// Creating literally | |
const onChange2: HandlerFor<'input', 'change'> = event => { | |
event.target.value; | |
event.target.focus(); | |
} | |
function App() { | |
return ( | |
<> | |
<input onChange={onChange} /> | |
<input onChange={onChange2} /> | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment