no-unnecessary-type-assertion
Disallow type assertions that do not change the type of an expression.
This rule prohibits using a type assertion that does not change the type of an expression.
Attributes
- Included in configs
- ✅ Recommended
- 🔒 Strict
- Fixable
- 🔧 Automated Fixer
- 💡 Suggestion Fixer
- 💭 Requires type information
Rule Details
This rule aims to prevent unnecessary type assertions.
Examples of code for this rule:
- ❌ Incorrect
- ✅ Correct
const foo = 3;
const bar = foo!;
const foo = <3>3;
type Foo = 3;
const foo = <Foo>3;
type Foo = 3;
const foo = 3 as Foo;
function foo(x: number): number {
return x!; // unnecessary non-null
}
const foo = <number>3;
const foo = 3 as number;
const foo = 'foo' as const;
function foo(x: number | undefined): number {
return x!;
}
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-unnecessary-type-assertion": "error"
}
};
Options
This rule accepts an options object with the following properties:
interface Options {
/**
* A list of type names to ignore.
*/
typesToIgnore?: string[];
}
const defaultOptions: Options = [{}];
typesToIgnore
With @typescript-eslint/no-unnecessary-type-assertion: ["error", { typesToIgnore: ['Foo'] }]
, the following is correct code":
type Foo = 3;
const foo: Foo = 3;
When Not To Use It
If you don't care about having no-op type assertions in your code, then you can turn off this rule.