0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScriptのstrictを段階的に有効にするためのtsconfigの設定順番

0
Posted at

TypeScriptのstrictを段階的に有効にするためのtsconfigの設定順番

TypeScriptは、JavaScriptの型安全性を高めるために利用される静的型付け言語です。TypeScriptのstrictオプションを有効にすることで、より厳格な型チェックが行われ、コードの品質が向上します。しかし、既存のプロジェクトでstrictを一気に有効にすると、多くのエラーが発生する可能性があります。

この記事では、TypeScriptのstrictを段階的に有効にするためのtsconfigの設定順番について説明します。

strictの設定順番

tsconfigstrictオプションは、次の順番で有効にすることが推奨されます。

  1. strictNullChecks: nullおよびundefinedの型チェックを有効にします。
  2. strictPropertyInitialization: プロパティの初期化を厳格にチェックします。
  3. strictBindCallApply: bind、call、applyメソッドの型チェックを有効にします。
  4. strictFunctionTypes: 関数の型チェックを厳格にします。
  5. strictTypeParameters: 型パラメータの型チェックを有効にします。
  6. strictClassInitialization: クラスの初期化を厳格にチェックします。
  7. strict: 上記のすべてのオプションを有効にします。

1. strictNullChecks

strictNullChecksは、nullおよびundefinedの型チェックを有効にします。次の例では、nameプロパティがnullであることをチェックします。

interface Person {
  name: string | null;
}

const person: Person = {
  name: null,
};

2. strictPropertyInitialization

strictPropertyInitializationは、プロパティの初期化を厳格にチェックします。次の例では、ageプロパティが初期化されていないことをチェックします。

interface Person {
  name: string;
  age: number;
}

const person: Person = {
  name: 'John',
};

3. strictBindCallApply

strictBindCallApplyは、bind、call、applyメソッドの型チェックを有効にします。次の例では、bindメソッドの型チェックを実行します。

function add(a: number, b: number): number {
  return a + b;
}

const boundAdd = add.bind(null, 1);

4. strictFunctionTypes

strictFunctionTypesは、関数の型チェックを厳格にします。次の例では、関数の型チェックを実行します。

function add(a: number, b: number): number {
  return a + b;
}

const result = add(1, '2');

5. strictTypeParameters

strictTypeParametersは、型パラメータの型チェックを有効にします。次の例では、型パラメータの型チェックを実行します。

interface Box<T> {
  value: T;
}

const box: Box<string> = {
  value: 1,
};

6. strictClassInitialization

strictClassInitializationは、クラスの初期化を厳格にチェックします。次の例では、クラスの初期化をチェックします。

class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

const person = new Person('John');

7. strict

strictは、上記のすべてのオプションを有効にします。次の例では、すべてのオプションを有効にします。

// tsconfig.json
{
  "compilerOptions": {
    "strict": true,
  },
}

詳しい手順はこちら → https://felixstudio0.gumroad.com/?utm_source=qiita&utm_medium=github_actions&utm_campaign=2026-q1&utm_content=qiita-footer

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?