Skip to main content

no-unnecessary-type-assertion

Disallow type assertions that do not change the type of an expression.

🔧

Some problems reported by this rule are automatically fixable by the --fix ESLint command line option.

💭

This rule requires type information to run.

TypeScript can be told an expression is a different type than expected using as type assertions. Leaving as assertions in the codebase increases visual clutter and harms code readability, so it's generally best practice to remove them if they don't change the type of an expression. This rule reports when a type assertion does not change the type of an expression.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-unnecessary-type-assertion": "error"
}
};
Try this rule in the playground ↗

Examples

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
}

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.

Resources