Skip to content

Commit b201640

Browse files
authored
type: add type guard (#527)
* type: add type guard * type: fix type * fix: fix * fix: fix * fix: fix
1 parent 15a195c commit b201640

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

src/ref.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,9 @@ export function supportRef(nodeOrComponent: any): boolean {
6262
return true;
6363
}
6464

65-
export function supportNodeRef(node: React.ReactNode): boolean {
65+
export function supportNodeRef<T = any>(
66+
node: React.ReactNode,
67+
): node is React.ReactElement & React.RefAttributes<T> {
6668
if (!isValidElement(node)) {
6769
return false;
6870
}

tests/ref.test.tsx

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,5 +186,17 @@ describe('ref', () => {
186186
expect(supportNodeRef(<FC />)).toBeFalsy();
187187
expect(supportNodeRef(<RefFC />)).toBeTruthy();
188188
});
189+
190+
it('ref', () => {
191+
const FC: React.FC = () => <div />;
192+
const RefFC = React.forwardRef<
193+
HTMLDivElement,
194+
React.HTMLAttributes<HTMLDivElement>
195+
>((props, ref) => <div {...props} ref={ref} />);
196+
const com = <FC />;
197+
const refCom = <RefFC ref={React.createRef()} />;
198+
expect(supportNodeRef(com) && com.ref).toBeFalsy();
199+
expect(supportNodeRef(refCom) && refCom.ref).toBeTruthy();
200+
});
189201
});
190202
});

0 commit comments

Comments
 (0)