SolvedDefinitelyTyped [styled-components] Cannot use forwardRef with styled component


Here is a simple repro. I can use forwarded ref on regular input, but not with styled one, it gives weird Typescript error, I am not sure what it means really.

https://codesandbox.io/s/o5ompq26j6

import * as React from 'react'
import styled from 'styled-components'

const StyledInput = styled.input`
  background-color: yellow;
`

export const WithInput = React.forwardRef<HTMLInputElement>((props, ref) => (
  <React.Fragment>
    <input ref={ref} />
    <StyledInput ref={ref} />
  </React.Fragment>
))
Type 'string | ((instance: HTMLInputElement | null) => any) | RefObject<HTMLInputElement> | undefined' is not assignable to type 'string | (string & ((instance: HTMLInputElement | null) => any)) | (string & RefObject<HTMLInputElement>) | (((instance: Component<ThemedOuterStyledProps<ClassAttributes<HTMLInputElement> & InputHTMLAttributes<HTMLInputElement> & { ...; }, any>, any, any> | null) => any) & string) | ... 5 more ... | undefined'.
  Type '(instance: HTMLInputElement | null) => any' is not assignable to type 'string | (string & ((instance: HTMLInputElement | null) => any)) | (string & RefObject<HTMLInputElement>) | (((instance: Component<ThemedOuterStyledProps<ClassAttributes<HTMLInputElement> & InputHTMLAttributes<HTMLInputElement> & { ...; }, any>, any, any> | null) => any) & string) | ... 5 more ... | undefined'.
    Type '(instance: HTMLInputElement | null) => any' is not assignable to type 'RefObject<Component<ThemedOuterStyledProps<ClassAttributes<HTMLInputElement> & InputHTMLAttributes<HTMLInputElement> & { invalid?: boolean | undefined; }, any>, any, any>> & RefObject<...>'.
      Type '(instance: HTMLInputElement | null) => any' is not assignable to type 'RefObject<Component<ThemedOuterStyledProps<ClassAttributes<HTMLInputElement> & InputHTMLAttributes<HTMLInputElement> & { invalid?: boolean | undefined; }, any>, any, any>>'.
        Property 'current' is missing in type '(instance: HTMLInputElement | null) => any'.
39 Answers

✔️Accepted Answer

At the moment I didn't come up with a solution yet. It looked harder than I expected. The issue is that what we called StyledComponentClass is not a class component anymore it is a forwarding component that needs to carry information of what it was created for to correctly accept refs.

A reduced repro:

const StyledInput = styled.input` `;
const inputRef = React.createRef<HTMLInputElement>();

<StyledInput ref={inputRef} />; // error

Change would require adding new generic parameters and might be breaking.
I'll keep you updated.

Other Answers:

My current workaround is to add as any.

ref={this.captureFn as any}

Closing as with @types/styled-components: 4.1.7 this seems to be working correctly now. Thank you @Jessidhia for amazing work!

Unfortunately for me this is not working yet. I'm still using the @cmrigney solution

This is still broken afaict

More Issues: