React: Type inference not working for ref callback
See original GitHub issueType inference is not working for the ref
callback prop.
I believe this is the same issue as in #7088, which was fixed over a year ago.
TypeScript Version: 2.3.2
Code
// A *self-contained* demonstration of the problem follows...
class Other extends React.Component<any, any> {
render() {
return <div />;
}
}
class Container extends React.Component<any, any> {
private _ref: Other;
render() {
// Parameter 'ref' implicitly has an 'any' type.
return <Other ref={ ref => this._ref = ref } />;
}
}
Expected behavior:
Type of parameter ref
should be inferred as Test
Actual behavior: Parameter ‘ref’ implicitly has an ‘any’ type.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:3
- Comments:13 (5 by maintainers)
Top Results From Across the Web
Type inference not working for React ref callback param #7088
This looks like a type inference issue with tsc 1.8.0+ (also nightly), but I'm not sure. It could also be because of typings....
Read more >Typescript react: Type inference is not working for callback refs
You can fix this by typing your useState function: const [refElement, setReference] = useState<HTMLDivElement | null>(null); .
Read more >Type inference is not working for callback refs-Reactjs
Coding example for the question Typescript react: Type inference is not working for callback refs-Reactjs.
Read more >React uses 'any' for useCallback parameters and there's no ...
I just realized that useCallback in React defines any[] as its method arguments so it's totally possible to define a useCallback where all ......
Read more >Documentation - Do's and Don'ts - TypeScript
Instead of Object , use the non-primitive object type (added in TypeScript 2.2) ... Don't use the return type any for callbacks whose...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
would love to see this get fixed!
Thank you, your example indeed works. Finally I had time to come up with a better example that doesn’t work for me. I’m probably doing something wrong I think:
When I try to explicitly set a type like
ref={(p: MyInput) => 0}
then I get following compiler error:When I try to set the type to
HTMLInputElement
I get:Clearly I have no idea what’s going on here and I’m just randomly throwing types at my code until the compiler stops complaining 😆