Typescript support for Refs
October 17, 2018 at 6:28amTypescript support for Refs
October 17, 2018 at 6:28amHey Guys! Congrats on v4!
Been migrating the codebase to v4 and refractoring the use of
innerRef
to just ref
But there is an incomprehensible (may be because I'm new) type error.
container = React.createRef<HTMLDivElement>();<Container ref={this.container}><p>Text</p></Container>
What should I be giving out the type of component as?
See a demo https://codesandbox.io/s/0p9wqmw24w
August 1, 2019 at 6:46pm
Hi , did you ever figure this one out? Upgrading to v4 today and my refs are all breaking.
Type 'RefObject<HTMLDivElement>' is not assignable to type 'string | (string & ((instance: HTMLDivElement | null) => any)) | (((instance: Component<ThemedOuterStyledProps<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, DefaultTheme>, ComponentState> | null) => any) & string) | (((instance: Component<...> | null) => any) & ((instance: HTMLDivElement | null)...'.Type 'RefObject<HTMLDivElement>' is not assignable to type '((instance: Component<ThemedOuterStyledProps<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, DefaultTheme>, ComponentState> | null) => any) & ((instance: HTMLDivElement | null) => any)'.Type 'RefObject<HTMLDivElement>' is not assignable to type '(instance: Component<ThemedOuterStyledProps<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, DefaultTheme>, ComponentState> | null) => any'.Type 'RefObject<HTMLDivElement>' provides no match for the signature '(instance: Component<ThemedOuterStyledProps<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, DefaultTheme>, ComponentState> | null): any'.ts(2322)index.d.ts(89, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<ThemedOuterStyledProps<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, DefaultTheme>, ComponentState>> & Readonly<...> & Readonly<...>'
For now I'm just typing all refs as
any
Also having to do
styled(Dropdown as any)
instead of styled(Dropdown)
August 2, 2019 at 11:53am
August 2, 2019 at 8:30pm
October 16, 2020 at 8:47pm
October 24, 2020 at 1:00am
November 24, 2020 at 11:35pm
Try ElementRef or ReactElement or JSX.Element
When i have this issue, I drill into the React library from my IDE to see what they define in the library declarations. (react is built in typescript). If youre using VSCode, it really doesnt do a good job of auto-completion which makes typing really easy. try IntelliJ Webstorm or IDEA (not freeware).