no-unnecessary-type-assertion
Disallow type assertions that do not change the type of an expression.
Extending "plugin:@typescript-eslint/recommended-type-checked"
in an ESLint configuration enables this rule.
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.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/no-unnecessary-type-assertion": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/no-unnecessary-type-assertion": "error"
}
};
Try this rule in the playground ↗
Examples
- ❌ Incorrect
- ✅ Correct
const foo = 3;
const bar = foo!;
Open in Playgroundconst foo = <number>(3 + 5);
Open in Playgroundtype Foo = number;
const foo = <Foo>(3 + 5);
Open in Playgroundtype Foo = number;
const foo = (3 + 5) as Foo;
Open in Playgroundconst foo = 'foo' as const;
Open in Playgroundfunction foo(x: number): number {
return x!; // unnecessary non-null
}
Open in Playgroundconst foo = <number>3;
Open in Playgroundconst foo = 3 as number;
Open in Playgroundlet foo = 'foo' as const;
Open in Playgroundfunction foo(x: number | undefined): number {
return x!;
}
Open in PlaygroundOptions
This rule accepts the following options:
type Options = [
{
/** A list of type names to ignore. */
typesToIgnore?: string[];
},
];
const defaultOptions: Options = [{}];
typesToIgnore
A list of type names to ignore. Default: []
.
With @typescript-eslint/no-unnecessary-type-assertion: ["error", { typesToIgnore: ['Foo'] }]
, the following is correct code:
type Foo = 3;
const foo: Foo = 3;
Open in PlaygroundWhen 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.
Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.
See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.