Skip to content

Commit

Permalink
fix: correct type inference for props when initialProps is used (#1421)
Browse files Browse the repository at this point in the history
* fix: correct type inference for props when initialProps is used

* Update src/__tests__/renderHook.test.tsx

* refactor: simplify type of Renderhook options

---------

Co-authored-by: pierrezimmermann <pierrez@nam.tech>
Co-authored-by: Maciej Jastrzebski <mdjastrzebski@gmail.com>
  • Loading branch information
3 people authored Jul 19, 2023
1 parent 5bb5d2d commit fa0c86e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 10 deletions.
34 changes: 34 additions & 0 deletions src/__tests__/renderHook.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,37 @@ test('allows wrapper components', async () => {

expect(result.current).toEqual('provided');
});

const useMyHook = (param: number | undefined) => {
return param;
};

test('props type is infered correctly when initial props is defined', () => {
const { result, rerender } = renderHook(
(num: number | undefined) => useMyHook(num),
{
initialProps: 5,
}
);

expect(result.current).toBe(5);

rerender(6);

expect(result.current).toBe(6);
});

test('props type is inferred correctly when initial props is explicitly undefined', () => {
const { result, rerender } = renderHook(
(num: number | undefined) => useMyHook(num),
{
initialProps: undefined,
}
);

expect(result.current).toBeUndefined();

rerender(6);

expect(result.current).toBe(6);
});
14 changes: 4 additions & 10 deletions src/renderHook.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,10 @@ export type RenderHookResult<Result, Props> = {
unmount: () => void;
};

export type RenderHookOptions<Props> = Props extends
| object
| string
| number
| boolean
? {
initialProps: Props;
wrapper?: ComponentType<any>;
}
: { wrapper?: ComponentType<any>; initialProps?: never } | undefined;
export type RenderHookOptions<Props> = {
initialProps?: Props;
wrapper?: ComponentType<any>;
};

export function renderHook<Result, Props>(
renderCallback: (props: Props) => Result,
Expand Down

0 comments on commit fa0c86e

Please sign in to comment.