Skip to content
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

React ref union types cause false errors #36659

Closed
just-boris opened this issue Feb 6, 2020 · 3 comments
Closed

React ref union types cause false errors #36659

just-boris opened this issue Feb 6, 2020 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@just-boris
Copy link

just-boris commented Feb 6, 2020

Search Terms

react ref union type

Suggestion

Currently React refs do not work when you applying it to different elements depending on some condition. I'd like to not have Typescript errors for this case

Use Cases

Sometimes we need to conditionally render different elements and attach refs to them:

function Button({ href }: { href: string }) {
    const ref = React.useRef<HTMLAnchorElement | HTMLButtonElement>()
    if (href) {
        return <a ref={ref}></a>
//               Type 'RefObject<HTMLAnchorElement | HTMLButtonElement>' is not assignable
//               to type 'RefObject<HTMLAnchorElement>'.
    }
    return <button ref={ref}></button>

}

This code is valid Javascript, but reports an error in Typescript.

Playground example

I think, this is also related to the general covariance issue: #10717 (comment)
But I am wondering if there could be a more simple solution to this particular case

@nmain100
Copy link

nmain100 commented Feb 6, 2020

#21759 could solve this, as when passing a ref object to React.createElement, only the write side is consumed.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Feb 26, 2020
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

@just-boris
Copy link
Author

just-boris commented Feb 29, 2020

Solved my issue via React.useImperativeHandle hook:

function Button({ href }: { href: string }, ref: React.Ref<{focus(): void}>) {
    const ref = React.useRef<any>()
    React.useImperativeHandle(ref, () => ({focus: () => ref.current && ref.current.focus}))
    if (href) {
        return <a ref={ref}></a>
    }
    return <button ref={ref}></button>

}

This way I am able to give component consumers type-safe API for refs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants