TypeScriptのstrictを段階的に有効にするためのtsconfigの設定順番
TypeScriptは、JavaScriptの型安全性を高めるために利用される静的型付け言語です。TypeScriptのstrictオプションを有効にすることで、より厳格な型チェックが行われ、コードの品質が向上します。しかし、既存のプロジェクトでstrictを一気に有効にすると、多くのエラーが発生する可能性があります。
この記事では、TypeScriptのstrictを段階的に有効にするためのtsconfigの設定順番について説明します。
strictの設定順番
tsconfigのstrictオプションは、次の順番で有効にすることが推奨されます。
-
strictNullChecks: nullおよびundefinedの型チェックを有効にします。 -
strictPropertyInitialization: プロパティの初期化を厳格にチェックします。 -
strictBindCallApply: bind、call、applyメソッドの型チェックを有効にします。 -
strictFunctionTypes: 関数の型チェックを厳格にします。 -
strictTypeParameters: 型パラメータの型チェックを有効にします。 -
strictClassInitialization: クラスの初期化を厳格にチェックします。 -
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,
},
}