Skip to content

Commit

Permalink
type: add type guard (#527)
Browse files Browse the repository at this point in the history
* type: add type guard

* type: fix type

* fix: fix

* fix: fix

* fix: fix
  • Loading branch information
li-jia-nan authored Apr 30, 2024
1 parent 15a195c commit b201640
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ export function supportRef(nodeOrComponent: any): boolean {
return true;
}

export function supportNodeRef(node: React.ReactNode): boolean {
export function supportNodeRef<T = any>(
node: React.ReactNode,
): node is React.ReactElement & React.RefAttributes<T> {
if (!isValidElement(node)) {
return false;
}
Expand Down
12 changes: 12 additions & 0 deletions tests/ref.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -186,5 +186,17 @@ describe('ref', () => {
expect(supportNodeRef(<FC />)).toBeFalsy();
expect(supportNodeRef(<RefFC />)).toBeTruthy();
});

it('ref', () => {
const FC: React.FC = () => <div />;
const RefFC = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>((props, ref) => <div {...props} ref={ref} />);
const com = <FC />;
const refCom = <RefFC ref={React.createRef()} />;
expect(supportNodeRef(com) && com.ref).toBeFalsy();
expect(supportNodeRef(refCom) && refCom.ref).toBeTruthy();
});
});
});

0 comments on commit b201640

Please sign in to comment.