Skip to content

Commit

Permalink
Merge pull request #181 from wellyshen/refactor-better-type-dx
Browse files Browse the repository at this point in the history
Refactor: simplify generic type setup
  • Loading branch information
wellyshen committed Jul 7, 2021
2 parents b1f48bd + 44769e5 commit e2f22c4
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/itchy-dogs-leave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-cool-virtual": patch
---

refactor: simplify generic type setup
21 changes: 19 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1333,12 +1333,29 @@ const Grid = () => {
### Working in TypeScript
React Cool Virtual is built with [TypeScript](https://www.typescriptlang.org), you can tell the hook what type of your **outer** and **inner** elements are as follows:
React Cool Virtual is built with [TypeScript](https://www.typescriptlang.org), you can tell the hook what type of your **outer** and **inner** elements are as follows.
If the outer element and inner element are different types:
```tsx
const App = () => {
// 1st is the `outerRef`, 2nd is the `innerRef`
const { outerRef, innerRef } = useVirtual<HTMLDivElement, HTMLDivElement>();
const { outerRef, innerRef } = useVirtual<HTMLDivElement, HTMLUListElement>();

return (
<div ref={outerRef}>
<ul ref={innerRef}>{/* Rendering items... */}</ul>
</div>
);
};
```
If the outer element and inner element are same types:
```tsx
const App = () => {
// By default, the `innerRef` will refer to the type of the `outerRef`
const { outerRef, innerRef } = useVirtual<HTMLDivElement>();

return (
<div ref={outerRef}>
Expand Down
4 changes: 2 additions & 2 deletions src/types/react-cool-virtual.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ declare module "react-cool-virtual" {

export interface Return<
O extends HTMLElement = HTMLElement,
I extends HTMLElement = HTMLElement
I extends HTMLElement = O
> {
outerRef: MutableRefObject<O | null>;
innerRef: MutableRefObject<I | null>;
Expand All @@ -126,6 +126,6 @@ declare module "react-cool-virtual" {

export default function useVirtual<
O extends HTMLElement = HTMLElement,
I extends HTMLElement = HTMLElement
I extends HTMLElement = O
>(config: Options): Return<O, I>;
}
2 changes: 1 addition & 1 deletion src/useVirtual.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const getInitItems = (itemSize: ItemSize, ssrItemCount?: SsrItemCount) => {

export default <
O extends HTMLElement = HTMLElement,
I extends HTMLElement = HTMLElement
I extends HTMLElement = O
>({
itemCount,
ssrItemCount,
Expand Down

0 comments on commit e2f22c4

Please sign in to comment.