Calling a JSX event handler explicitly

How can I call an event handler explicitly?
const handleFocus = (e: FocusEvent) => {
// perform some operation

props.onFocus?.(e)
}
const handleFocus = (e: FocusEvent) => {
// perform some operation

props.onFocus?.(e)
}
It gives the compilation error:
This expression is not callable. Not all constituents of type 'FocusEventHandlerUnion<HTMLInputElement, FocusEvent>' are callable. Type 'BoundEventHandler<HTMLInputElement, FocusEvent, FocusEventHandler<HTMLInputElement, FocusEvent>>' has no call signatures.
Is it safe to simply check if it is a function, or not that simple? Thanks
3 Replies
bigmistqke
bigmistqke3w ago
i suppose you are doing something like props: ComponentProps<"dive">
Is it safe to simply check if it is a function, or not that simple?
yes 👍 i often do props: Omit<ComponentProps<"div">, 'onFocus'> & { onFocus(event: FocusEvent & { currentTarget: HTMLDivElement }): void } it's because solid also accepts
const handler = (data, event) => {
console.log("Data:", data, "Event:", event);
};

<button onClick={[handler, "Hello!"]}>Click Me</button>;
const handler = (data, event) => {
console.log("Data:", data, "Event:", event);
};

<button onClick={[handler, "Hello!"]}>Click Me</button>;
documentation
snorbi
snorbiOP3w ago
I didn't know this trick with Omit, it is nice, thanks 🙂
peerreynders
peerreynders3w ago
Pick<Type,Keys> is similarly handy.
Documentation - Utility Types
Types which are globally included in TypeScript

Did you find this page helpful?