Definitelytyped: How to correctly define a reference (React.RefObject<StyledComponentClass>) for styled-components (for TypeScript)?

Created on 2 Nov 2018  路  4Comments  路  Source: DefinitelyTyped/DefinitelyTyped

I tried using the @types/styled-components package and had problems.

How to correctly define a reference for styled-components?

I wrote the following test code:

import React, {Component, RefObject, ReactNode} from 'react';
import styled, {StyledComponentClass} from 'styled-components';

type TModalShadowContainer = StyledComponentClass<{}, any>;

const ModalShadowContainer: TModalShadowContainer = styled.div` 
    background-color: black;
`;

export default class Modal extends Component {

    private readonly modalRef: RefObject<TModalShadowContainer>;

    constructor(props: {}) {
        super(props);
        this.modalRef = React.createRef<TModalShadowContainer>();
    }

    public render(): ReactNode {
        return (
            <ModalShadowContainer ref={this.modalRef}>
                {this.props.children}
            </ModalShadowContainer>
        );
    }

}

The error appears on the line:

<ModalShadowContainer ref={this.modalRef}>

Error text:

Type 'RefObject<StyledComponentClass<{}, {}, {}>>' is not assignable to type 'string | ((instance: Component<{ as?: string | ComponentClass<any, any> | StatelessComponent<any> | undefined; theme?: {} | undefined; }, any, any> | null) => any) | RefObject<Component<{ ...; }, any, any>> | undefined'.
  Type 'RefObject<StyledComponentClass<{}, {}, {}>>' is not assignable to type 'RefObject<Component<{ as?: string | ComponentClass<any, any> | StatelessComponent<any> | undefined; theme?: {} | undefined; }, any, any>>'.
    Type 'StyledComponentClass<{}, {}, {}>' is not assignable to type 'Component<{ as?: string | ComponentClass<any, any> | StatelessComponent<any> | undefined; theme?: {} | undefined; }, any, any>'.
      Property 'setState' is missing in type 'StyledComponentClass<{}, {}, {}>'.

How to describe (define) a ref in TypeScript lang?

Since everyone is trying to convince me not to do it, I have to refer to the original sources, namely:

https://www.styled-components.com/docs/advanced#refs
https://reactjs.org/docs/refs-and-the-dom.html#creating-refs

Most helpful comment

@dawidk92 Does the AnyStyledComponent type fulfill your needs?

All 4 comments

interface StyledComponentClass

had been removed in @types/[email protected]. What should we have been using instead of it?

Beside of that question is there any option to follow changes in typings? Some kind of changelog?

@dawidk92 Does the AnyStyledComponent type fulfill your needs?

@tp yes, thank you :)

Was this page helpful?
0 / 5 - 0 ratings