Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to bind EventCallable<void> to an optional callback #92

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 7 additions & 9 deletions public-types/reflect.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,21 @@ type Hooks<Props> = {
| ((props: Props) => unknown);
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type VoidCallback<T> = T extends (...args: any[]) => infer R ? () => R : never;

/**
* `bind` object type:
* prop key -> store (unwrapped to reactive subscription) or any other value (used as is)
*
* Also handles some edge-cases like enforcing type inference for inlined callbacks
*/
type BindFromProps<Props> = {
[K in keyof Props]?: K extends UnbindableProps
? never
: Props[K] extends (...args: any[]) => any
? // To force TS infer types for any provided callback
| ((...args: Parameters<Props[K]>) => ReturnType<Props[K]>)
// Edge-case: allow to pass an event listener without any parameters (e.g. onClick: () => ...)
| (() => ReturnType<Props[K]>)
// Edge-case: allow to pass a Store, which contains a function
:
| Store<Props[K]>
: Store<Props[K]> | Props[K];
| Props[K]
// case: allow Event<void> for callbacks with arbitrary arguments
| VoidCallback<Props[K]>;
};

/**
Expand Down
20 changes: 20 additions & 0 deletions type-tests/types-reflect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,26 @@ import { expectType } from 'tsd';
expectType<React.FC>(ReflectedButton);
}

// reflect should allow passing Event<void> as callback to optional event handlers
{
const Button: React.FC<{
onOptional?: React.EventHandler<React.MouseEvent<HTMLButtonElement>>;
onNull: React.MouseEventHandler<HTMLButtonElement> | null;
}> = () => null;

const event = createEvent<void>();

const ReflectedButton = reflect({
view: Button,
bind: {
onOptional: event,
onNull: event,
},
});

expectType<React.FC>(ReflectedButton);
}

// reflect should not allow binding ref
{
const Text = React.forwardRef(
Expand Down