From e37dc3fef085b8e633eb1b8cd534fddb439762b3 Mon Sep 17 00:00:00 2001 From: Rasmus Eneman Date: Tue, 31 Mar 2020 02:16:10 +0200 Subject: [PATCH] [react] forwardRefs ref object should be mutable (#43265) Please fill in this template. - [x] Use a meaningful title for the pull request. Include the name of the package modified. - [x] Test the change in your own code. (Compile and run.) - [x] Add or edit tests to reflect the change. (Run with `npm test`.) - [x] Follow the advice from the [readme](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#make-a-pull-request). - [x] Avoid [common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#common-mistakes). - [x] Run `npm run lint package-name` (or `tsc` if no `tslint.json` is present). Select one of these and delete the others: If changing an existing definition: - [x] Provide a URL to documentation or source code which provides context for the suggested changes: #31065, #39062 - [x] If this PR brings the type definitions up to date with a new version of the JS library, update the version number in the header. - [x] If you are making substantial changes, consider adding a `tslint.json` containing `{ "extends": "dtslint/dt.json" }`. If for reason the any rule need to be disabled, disable it for that line using `// tslint:disable-next-line [ruleName]` and not for whole package so that the need for disabling can be reviewed. Fixes #39062 --- types/react/index.d.ts | 2 +- types/react/test/index.ts | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 7300ff6e99..00a0f0a3be 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -560,7 +560,7 @@ declare namespace React { } interface ForwardRefRenderFunction { - (props: PropsWithChildren

, ref: Ref): ReactElement | null; + (props: PropsWithChildren

, ref: ((instance: T | null) => void) | MutableRefObject | null): ReactElement | null; displayName?: string; // explicit rejected with `never` required due to // https://github.com/microsoft/TypeScript/issues/36826 diff --git a/types/react/test/index.ts b/types/react/test/index.ts index b74bb5f98b..0d1c055872 100644 --- a/types/react/test/index.ts +++ b/types/react/test/index.ts @@ -439,6 +439,17 @@ function RefCarryingComponent() { }, ); } +const ForwardingRefComponent2 = React.forwardRef((props, ref) => { + return React.createElement('div', { + ref(e: HTMLDivElement) { + if (typeof ref === 'function') { + ref(e); + } else if (ref) { + ref.current = e; + } + } + }); +}); const MemoizedForwardingRefComponent = React.memo(ForwardingRefComponent); const LazyComponent = React.lazy(() => Promise.resolve({ default: RefComponent }));