Yarn Version Manager
@types/... *
version resolution
TL;DR
Add the following lines, and replace "17.0.47" with your expected version, to your package.json. Normally you should keep @types/react
at the same major version with react
. So, consider using ^
specifier.
"resolutions": {
"@types/react": "17.0.47"
},
Explanation
Many typescript packages may depend on "@types/react" "*"
for React typing. However, without further specification, the *
will be resolved to the latest version.
This will be problematic if the latest React version introduces a breaking change to the current version. For example, I once experienced an error message shown below:
$ <REDACTED>/node_modules/.bin/tsc
src/components/Gallery/index.tsx:13:6 - error TS2786: 'Masonry' cannot be used as a JSX component.
Its instance type 'Component<MasonryPropTypes, any, any>' is not a valid JSX element.
The types returned by 'render()' are incompatible between these types.
Type 'React.ReactNode' is not assignable to type 'import("<REDACTED>/node_modules/@types/react-router-config/node_modules/@types/react/index").ReactNode'.
Type '{}' is not assignable to type 'ReactNode'.
13 <Masonry options={masonryOptions}>
~~~~~~~
It turns out that I have multiple @types/react
installed. Even though I have explicitly required @types/react 17.0.47
in devDependencies, the @types/react *
required by other dependencies (such as @types/react-router-config
in this case) is still resolved to the latest v18.0.14.
See the yarn.lock
file
By adding the resolutions
configuration to package.json, the @types/react
package is pointing correctly to the React version used (v17), resolving this error message.