no-unused-expressions
Disallow unused expressions.
✅
Extending "plugin:@typescript-eslint/recommended"
in an ESLint configuration enables this rule.
This rule extends the base eslint/no-unused-expressions
rule.
It supports TypeScript-specific expressions:
- Marks directives in modules declarations (
"use strict"
, etc.) as not unused - Marks the following expressions as unused if their wrapped value expressions are unused:
- Assertion expressions:
x as number;
,x!;
,<number>x;
- Instantiation expressions:
Set<number>;
- Assertion expressions:
Although the type expressions never have runtime side effects (that is, x!;
is the same as x;
), they can be used to assert types for testing purposes.
Examples
- ❌ Incorrect
- ✅ Correct
Set<number>;
1 as number;
window!;
Open in Playgroundfunction getSet() {
return Set;
}
// Funtion calls are allowed, so type expressions that wrap function calls are allowed
getSet()<number>;
getSet() as Set<unknown>;
getSet()!;
// Namespaces can have directives
namespace A {
'use strict';
}
Open in PlaygroundOptions
See eslint/no-unused-expressions
's options.
How to Use
- Flat Config
- Legacy Config
eslint.config.mjs
export default tseslint.config({
rules: {
// Note: you must disable the base rule as it can report incorrect errors
"no-unused-expressions": "off",
"@typescript-eslint/no-unused-expressions": "error"
}
});
.eslintrc.cjs
module.exports = {
"rules": {
// Note: you must disable the base rule as it can report incorrect errors
"no-unused-expressions": "off",
"@typescript-eslint/no-unused-expressions": "error"
}
};
Try this rule in the playground ↗