環境
- Mac OSX: v11.2.1
- node: v16.15.1
- yarn: v1.22.18
エラー詳細
-
yarn startでコンパイルを試みたところ、以下のエラーにより失敗
('Menu'はsemantic-ui-reactからインポートしたコンポーネント)
TypeScript error in /xxxx/App.tsx(28,8):
'Menu' cannot be used as a JSX component.
Its instance type 'Component<MenuProps, 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("/Users/ayakahidaka/Documents/random-training-timer-front/node_modules/@types/react-dom/node_modules/@types/react/index").ReactNode'. TS2786
26 | return (
27 | <div>
> 28 | <Menu
| ^
29 | as={Menu}
30 | >
- エラー発生時の
package.json(一部抜粋)
{
"dependencies": {
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"react": "^17.0.0",
"react-dom": "^17.0.0",
"react-scripts": "4.0.3",
"typescript": "^4.1.2",
...
}
...
}
解決方法
- 参考にしたサイト: NPM package cannot be used as a JSX Component - Type errors
-
package.jsonに以下の記述を追加- バージョンは
@types/react-domと同じものを設定
- バージョンは
"resolutions": {
"@types/react": "^17.0.0"
}
解説
解決前後の変化
- 参考にしたサイト内の解説によると、
@types/react-domは@types/reactのメジャーリリースバージョンに依存するとのこと-
package.jsonで指定した@types/reactのバージョンには依存しない模様
-
- 修正前後の
yarn.lockを比較すると確かに解説通り(左: 修正前、右: 修正後)
resolutionsとは?
- yarnのドキュメント (Selective dependency resolutions | Yarn)から引用
Yarn supports selective version resolutions, which lets you define custom package versions or ranges inside your dependencies through the resolutions field in your package.json file. Normally, this would require manual edits in the yarn.lock file.
- yarnで依存関係に用いるカスタムパッケージのバージョンを指定できる
-
yarn.lockを直接編集せず、package.json内に記述することで実現可能