Reputation: 721
How to correctly define a reference for styled-components?
I wrote the following test code. This is a refined code, unlike the previous one (How to correctly define a reference (React.RefObject) for styled-components (for TypeScript)?). Added reference type StyledComponentClass< {}, any>
.
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?
Upvotes: 4
Views: 3625
Reputation: 1265
Maybe this helps.
type MamkinHackerType<T> = T extends StyledComponentClass<React.DetailedHTMLProps<React.HTMLAttributes<infer ElementType>, infer ElementType>, infer T, infer H>
? ElementType & React.Component<React.DetailedHTMLProps<React.HTMLAttributes<ElementType>, ElementType> & T & H>
: never
;
private readonly modalRef = React.createRef<MamkinHackerType<typeof ModalShadowContainer>>();
Upvotes: 1