LoginSignup
2
1

型アサーションをLintで禁止にしたい

Last updated at Posted at 2024-03-01

1. 結論

こちらを使うと良いそうです!

2. 背景

const elm = hoge as HTMLInputElement;

このような記述はよく見ると思います。
型アサーションはその変数が如何なる値でもasの後の型として型チェックされます。
その為、実行時にエラーが起きることもあります。
社内では極力使わないようにしたいというコーディングルールになっています。

そこでeslintで、そのようなルールはあるのか調べて見ようと思ったのが経緯です。

3. 型アサーションを禁止にするプラグインを調査

以下がヒットしました。
typescript-eslintと、tslintでありそうです。

3.1. typescript-eslint

This rule reports when a type assertion does not change the type of an expression

不要な型アサーションを禁止にするものです。

3.2. TsLint

tslintにもno-unnecessary-type-assertionというruleがあったのですが、以下のようにdeprecatedされていました。

:warning: TSLint has been deprecated as of 2019.

3.3. EsLint

pluginでありました。

eslint-plugin-no-type-assertion

Disallow type assertions in TypeScript code. The rule will forbid both as operator and the angle-bracketed syntax, unless used for const assertions or with the unknown type

これでできますね。
しかもconst assertionはエラーにしないのはありがたいです!

⚠️eslint-plugin-no-type-assertionは非Nullアサーションも禁止にしてしまう

The rule also forbids non-null assertions.

4.その他

型アサーションはcast(キャスト)とは異なる

Type assertions are also commonly referred as "type casting" in TypeScript. However, that term is technically slightly different to what is understood by type casting in other languages. Type assertions are a way to say to the TypeScript compiler, "I know better than you, it's actually this different type!".

型アサーションはcastともよく言われますが、厳密には違います。

5.参考

最後に

コーディングルールをlinterに任せて、レビュワーの負担を減らしたいです

英語版の記事はこちら

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