strictBindCallApply
strictBindCallApplyはbind、call、applyの型チェックを厳しくするコンパイラオプションです。
- デフォルト: strictが有効の場合は
true、それ以外はfalse - 追加されたバージョン: 3.2
- TypeScript公式が有効化推奨
bind、call、applyが型チェックされない
strictBindCallApplyがfalse(TypeScriptのデフォルト)の場合、ビルトイン関数bind、call、applyの引数の型をチェックしません。
ts// 引数が文字列型の関数functionfn (x : string) {}// 渡す引数は数値型だが、警告は出ないfn .call (undefined , 122);
ts// 引数が文字列型の関数functionfn (x : string) {}// 渡す引数は数値型だが、警告は出ないfn .call (undefined , 122);
bind、call、applyで呼び出す関数の戻り値型注釈は無視され、戻り値の型はanyになります。
tsfunctionfn (): string {return "str";}constx =fn .call (undefined );
tsfunctionfn (): string {return "str";}constx =fn .call (undefined );
strictBindCallApplyがfalseの場合、実行時エラーが発生する恐れがあります。
tsfunctionfn (x : string) {x .toUpperCase ();}constx =fn .call (undefined , 123);
tsfunctionfn (x : string) {x .toUpperCase ();}constx =fn .call (undefined , 123);
bind、call、applyの型チェックを行う
strictBindCallApplyをtrueにすると、bind、call、applyの型チェックが行われます。
tsfunctionfn (x : string) {}Argument of type 'number' is not assignable to parameter of type 'string'.2345Argument of type 'number' is not assignable to parameter of type 'string'.fn .call (undefined ,123 );
tsfunctionfn (x : string) {}Argument of type 'number' is not assignable to parameter of type 'string'.2345Argument of type 'number' is not assignable to parameter of type 'string'.fn .call (undefined ,123 );
加えて、戻り値の型は呼び出す関数の戻り値型になります。
tsfunctionfn (): string {return "str";}constx =fn .call (undefined );
tsfunctionfn (): string {return "str";}constx =fn .call (undefined );
戻り値に型がつくため、補完が効くメリットもあります。
tsfunctionfn (): string {return "str";}conststr =fn .call (undefined );str .toU ;
tsfunctionfn (): string {return "str";}conststr =fn .call (undefined );str .toU ;
strictBindCallApplyは有効にするのがお勧めです。
学びをシェアする
TypeScriptのstrictBindCallApplyはbind、call、applyの型チェックを厳しくするコンパイラオプション
【falseの場合】
❌引数の型チェックがされない
⚠️戻り値はanyになる
【trueの場合】
✅引数の型チェックがされる
💚戻り値に型がつく
👍有効化推奨
『サバイバルTypeScript』より
関連情報
📄️ strict
strict系のオプションを一括で有効化する