DEV Community


Posted on • Updated on

How to ban type assertions with lint

1. conclusion

They say you can use this one!

2. background

const elm = hoge as HTMLInputElement;.
Enter fullscreen mode Exit fullscreen mode

You will often see statements like this.
Type assertions are type-checked as the type after as no matter what the value of the variable is.
This can cause errors at runtime.
We have a coding rule in our company that we try not to use them as much as possible.

So I decided to check if there is such a rule in eslint.

3. investigate plugins that prohibit type assertions

I found the following hits
typescript-eslint and tslint.

3.1. typescript-eslint

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

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

3.2. TsLint

tslint also had a rule no-unnecessary-type-assertion, but it was deprecated as follows

⚠️ tslint has been deprecated as of 2019.

3.3. EsLint

It was in plugin.


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

This will do it.
And it's nice to know that const assertions are not an error!

⚠️eslint-plugin-no-type-assertion also forbids non-null assertions!

The rule also forbids non-null assertions.

4. Other

Type assertions are different from casts.

Type assertions are also commonly referred as "type casting" in TypeScript. Type assertions are a way to say to the TypeScript compiler, "I know better than you, it's actually this different type! !".

Type assertions are also often referred to as casts, but strictly speaking they are not.


I would like to leave the coding rules to linter and reduce the burden on reviewers!

Thanks for looking.
This is my first post🎉

Top comments (0)