Skip to content

Add immutable forwardRef typing alternative #323

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 5, 2020

Conversation

kripod
Copy link
Contributor

@kripod kripod commented Oct 3, 2020

No description provided.

@@ -28,6 +28,20 @@ export const FancyButton = React.forwardRef<Ref, Props>((props, ref) => (
));
```

`forwardRef` alternative without mutability:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i dont understand what "without mutability" means. do you mind elaborating in here? how does this materially differ from the example above?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

React.forwardRef<HTMLElement, Props> assigns the type ((instance: T | null) => void) | MutableRefObject<T | null> | null to the ref parameter. It's a MutableRefObject<T | null>, unlike with React.Ref<T>. The latter returns ((instance: T | null) => void) | RefObject<T> | null, which seems to be an improvement.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

which seems to be an improvement.

We should explain this in the cheatsheet where this would be an improvement. It would always be an improvement then you should propose the change to @types/react.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

alright @kripod, i understand where you are coming from, and agree with @eps1lon that we should fix this in @types. wanna open up an issue over there?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the discussion!

It appears that an opposing issue was raised and a PR has been merged to make the ref parameter of forwardRef mutable.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wow. we both learned something today...

@swyxio swyxio merged commit d92e94a into typescript-cheatsheets:main Oct 5, 2020
@kripod kripod deleted the patch-2 branch October 6, 2020 10:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants