概要
Next.js
にTypeScript
を導入したら設定がゆるふわだったので修正したという話
アプリケーションの作成と TypeScript の導入
まずはアプリケーションを作成する。
$ npx create-next-app next-ts
次に必要なパッケージをインストールする。
$ yarn add -D typescript @types/react @types/react-dom @types/node
続いて拡張子を変更する。
$ mv pages/index.js pages/_app.tsx
$ mv pages/_app.js pages/_app.tsx
$ mv pages/api/hello.js pages/api/hello.ts
最後にアプリを起動する。
$ yarn dev
すると自動で下記ファイルが作成される。
next-env.d.ts
/// <reference types="next" />
/// <reference types="next/types/global" />
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules"
]
}
無事に http://lobalhost:3000 で画面表示されて完了(?)。
Any が許容されていたデフォルト設定
「あれ?何か違和感。」
とりあえず適当なファイルを確認する。
_app.tsx
import '../styles/globals.css'
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
「そういえば引数の型を指定してしない。any
で許容されている。」
システムが許しても私は許さない。設定ファイルを確認する。
tsconfig.json
{
"compilerOptions": {
・・・
"strict": false
・・・
}
}
「なぜデフォルトがstrict: false
なのだろうか。」
strict: true
に修正する。これでnoImplicitAny
などの設定が有効化される。
暗黙的なany
が 無事にエラー になったので各ファイルも修正する。
_app.tsx
import '../styles/globals.css'
import { AppProps } from 'next/app'
function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
export default MyApp
hello.ts
import { NextApiRequest, NextApiResponse } from 'next'
export default (req: NextApiRequest, res: NextApiResponse) => {
res.statusCode = 200
res.json({ name: 'John Doe' })
}
TypeScript
の恩恵は有り難く享受していきたい。