フロントエンド開発の先端を突っ走るNext.js
next.js アプリの初期化( npx create-next-app@latest <アプリ名> ) または yarn create next-app <アプリ名> または bun create next-app <アプリ名> )

eslint で typescript エラーを吐かせる

● eslint で typescript エラーを吐かせる(eslintプラグインを使う方法)

npm i -D @typescript-eslint/eslint-plugin

.eslintrc.json に 吐かせたいルールを追記することで、typescriptエラーも表示させることができます。

{
  "extends": [
    "plugin:@typescript-eslint/recommended",
    "next/core-web-vitals"
  ],
  "rules": {
    "@typescript-eslint/no-unused-vars": "warn",
    "@typescript-eslint/no-explicit-any": "warn"
  }
}

● lint-staged で typescript エラーを吐かせる(tscを使う方法)

  "lint-staged": {
    "./**/*.{js,jsx,ts,tsx}": [
      "tsc --pretty --noEmit"
    ],
  },

● typescript のエラーとなるコード

// 1. 型の不一致
const numberVar: number = "this is not a number";

// 2. 未定義の変数の使用
console.log(undeclaredVariable); // 未定義の変数


// 3. 関数のパラメータの型ミスマッチ
function addNumbers(a: number, b: number) {
    return a + b;
}
addNumbers(1, "2"); // 第二引数が不正な型

// 4. プロパティが存在しない 
const obj = { name: "Alice", age: 30 };
console.log(obj.salary);

// 5. 関数の必須引数の欠如
function greet(name: string) {
    return `Hello, ${name}!`;
}
greet();


// 6. インターフェースの実装エラー
interface Person {
    name: string;
    age: number;
}
const alice: Person = { name: "Alice" };

// 7. ユニオン型の誤用
type StringOrNumber = string | number;
const value: StringOrNumber = true;
No.2498
04/05 11:09

edit