LoginSignup
0
0

More than 3 years have passed since last update.

Next.js に TypeScript を導入したのに Any が許容されていた話

Last updated at Posted at 2020-11-22

概要

Next.jsTypeScriptを導入したら設定がゆるふわだったので修正したという話

アプリケーションの作成と 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の恩恵は有り難く享受していきたい。

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0