ReactプロジェクトをTypeScript化する
手順
$ npm install typescript ts-loader --save-dev
tsconfigの設定
noImplictAny以下ははじめはfalseでいいかも
code:tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "es2015",
"jsx": "react",
"esModuleInterop": true,
"moduleResolution": "node",
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitThis": true
}
}
webpack.config.jsの設定
一例
code:diff
module.exports = {
- entry: path.join(srcPath, "index.jsx"),
+ entry: path.join(srcPath, "index.tsx"),
..
module: {
rules: [
..
{
- test: /\.jsx?$/,
+ test: /\.tsx?$/,
exclude: /node_modules/,
- loader: "babel-loader",
+ loader: "ts-loader",
},
],
},
resolve: {
},
..
外部ライブラリの型定義をインストール
$ npm install @types/react @types/react-dom @types/react-router-dom --save-dev
$ npm install @types/react-helmet @types/lodash.difference @types/material-ui --save-dev
$ rename 's/\.jsx\z/.tsx/' src/**/*.jsx
ひたすらコンパイルエラーを取り除く(調べながら)
参考
union型で少しつまづいた
asで型を教えてあげる必要があった
型アサーション
nullになる可能性があることを教えられる新鮮な体験
きちんと早期リターンすれば問題ない