2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TypeScriptで関数の引数テストを書いた場合の型エラーを無効化する

Posted at

TypeScriptで関数を書く時、引数の型を定義することで、想定していない引数が入り込むのを防ぐことができます。

下の例は引数を二乗して返すだけの関数です。引数をnumber型に限定することで、TypeScriptを使っている限りは、square(null)のように数値以外の引数で呼ぶことができなくなります。(トランスパイル時にエラーになる)

const square = (num: number): number => {
  return num * num;
}; 

自分でその関数を使うだけならこれで十分ですが、npm等でmoduleとして配布する場合、他の人がTypeScriptを使ってくれるとは限りませんから、想定していない引数が渡された場合のエラーハンドリングをしておきたいところです。

const square = (num: number): number => {
  if(typeof num !== "number"){
    Error("Augument must be a number.");
  }
  return num * num;
}; 

ところがこの関数の引数テストをTypeScriptで書こうとすると、そもそもnumber以外の引数を渡すことが出来ないため、テスト実行時にエラーになってしまいます。

describe("test", () => {
  it("test square()", () => {
    expect(() => {
      square(null); // Argument of type 'null' is not assignable to parameter of type 'number'.
    }).toThrow();
  });
});

エラーを解消するためには、引数のnullをany型に型アサーションしてあげる必要があります。
が、@typescript-eslintを使っている場合、今度は@typescript-eslint/no-explicit-anyのwarningが出るようになります。

describe("test", () => {
  it("test square()", () => {
    expect(() => {
      square(null as any); // Unexpected any. Specify a different type
    }).toThrow();
  });
});

warningなので無視することもできますが、コードに問題がある訳ではないのでできるなら消したいです。
このような場合、テストコードの先頭にeslintの設定を記述することで、ファイル単位で特定のルールを無効化することができます。

/* eslint @typescript-eslint/no-explicit-any: 0 */
describe("test", () => {
  it("test square()", () => {
    expect(() => {
      square(null as any);
    }).toThrow();
  });
});

これでlinterのwarningもトランスパイルエラーも発生させることなく、引数テストを実行できます。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?