1. conclusion
https://www.npmjs.com/package/eslint-plugin-no-type-assertion
They say you can use this one!
2. background
const elm = hoge as HTMLInputElement;.
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.
https://github.com/typescript-eslint/typescript-eslint/issues/1310
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
https://palantir.github.io/tslint/
⚠️ tslint has been deprecated as of 2019.
3.3. EsLint
It was in plugin.
eslint-plugin-no-type-assertion
https://www.npmjs.com/package/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
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.
https://typescript-eslint.io/rules/consistent-type-assertions
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.
Finally.
I would like to leave the coding rules to linter and reduce the burden on reviewers!
Thanks for looking.
This is my dev.to first post🎉
Top comments (0)