Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add no-unsafe-unary-minus rule #7390

Merged
merged 8 commits into from Nov 13, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 37 additions & 0 deletions packages/eslint-plugin/docs/rules/no-unsafe-unary-minus.md
@@ -0,0 +1,37 @@
---
description: 'Require unary negation to take a number.'
---

> 🛑 This file is source code, not the primary documentation location! 🛑
>
> See **https://typescript-eslint.io/rules/no-unsafe-unary-minus** for documentation.

TypeScript does not prevent you from putting a minus sign before things other than numbers:

```ts
const s = 'hello';
const x = -s; // x is NaN
```

This rule restricts the unary `-` operator to `number | bigint`.

## Examples
samestep marked this conversation as resolved.
Show resolved Hide resolved

### ❌ Incorrect

```ts
const f = (a: string) => -a;
const g = (a: {}) => -a;
```

### ✅ Correct

```ts
const a = -42;
const b = -42n;
const f1 = (a: number) => -a;
const f2 = (a: bigint) => -a;
const f3 = (a: number | bigint) => -a;
const f4 = (a: any) => -a;
const f5 = (a: 1 | 2) => -a;
```
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/all.ts
Expand Up @@ -123,6 +123,7 @@ export = {
'@typescript-eslint/no-unsafe-enum-comparison': 'error',
'@typescript-eslint/no-unsafe-member-access': 'error',
'@typescript-eslint/no-unsafe-return': 'error',
'@typescript-eslint/no-unsafe-unary-minus': 'error',
'no-unused-expressions': 'off',
'@typescript-eslint/no-unused-expressions': 'error',
'no-unused-vars': 'off',
Expand Down
2 changes: 2 additions & 0 deletions packages/eslint-plugin/src/rules/index.ts
Expand Up @@ -86,6 +86,7 @@ import noUnsafeDeclarationMerging from './no-unsafe-declaration-merging';
import noUnsafeEnumComparison from './no-unsafe-enum-comparison';
import noUnsafeMemberAccess from './no-unsafe-member-access';
import noUnsafeReturn from './no-unsafe-return';
import noUnsafeUnaryMinus from './no-unsafe-unary-minus';
import noUnusedExpressions from './no-unused-expressions';
import noUnusedVars from './no-unused-vars';
import noUseBeforeDefine from './no-use-before-define';
Expand Down Expand Up @@ -221,6 +222,7 @@ export default {
'no-unsafe-enum-comparison': noUnsafeEnumComparison,
'no-unsafe-member-access': noUnsafeMemberAccess,
'no-unsafe-return': noUnsafeReturn,
'no-unsafe-unary-minus': noUnsafeUnaryMinus,
'no-unused-expressions': noUnusedExpressions,
'no-unused-vars': noUnusedVars,
'no-use-before-define': noUseBeforeDefine,
Expand Down
55 changes: 55 additions & 0 deletions packages/eslint-plugin/src/rules/no-unsafe-unary-minus.ts
@@ -0,0 +1,55 @@
import type * as ts from 'typescript';

import * as util from '../util';

interface TypeChecker extends ts.TypeChecker {
// https://github.com/microsoft/TypeScript/issues/9879
isTypeAssignableTo(source: ts.Type, target: ts.Type): boolean;
getUnionType(types: ts.Type[]): ts.Type;
samestep marked this conversation as resolved.
Show resolved Hide resolved
}

type Options = [];
type MessageIds = 'unaryMinus';

export default util.createRule<Options, MessageIds>({
name: 'no-unsafe-unary-minus',
meta: {
type: 'problem',
docs: {
description: 'Require unary negation to take a number',
requiresTypeChecking: true,
},
messages: {
unaryMinus: 'Invalid type "{{type}}" of template literal expression.',
},
schema: [],
},
defaultOptions: [],
create(context) {
return {
UnaryExpression(node): void {
if (node.operator !== '-') {
return;
}
const services = util.getParserServices(context);
const argType = services.getTypeAtLocation(node.argument);
const checker = services.program.getTypeChecker() as TypeChecker;
if (
!checker.isTypeAssignableTo(
argType,
checker.getUnionType([
checker.getNumberType(), // first exposed in TypeScript v5.1
checker.getBigIntType(), // first added in TypeScript v5.1
]),
samestep marked this conversation as resolved.
Show resolved Hide resolved
)
) {
context.report({
messageId: 'unaryMinus',
node,
data: { type: checker.typeToString(argType) },
});
}
},
};
},
});
31 changes: 31 additions & 0 deletions packages/eslint-plugin/tests/rules/no-unsafe-unary-minus.test.ts
@@ -0,0 +1,31 @@
import { RuleTester } from '@typescript-eslint/rule-tester';

import rule from '../../src/rules/no-unsafe-unary-minus';
import { getFixturesRootDir } from '../RuleTester';

const rootDir = getFixturesRootDir();
const ruleTester = new RuleTester({
parserOptions: {
ecmaVersion: 2015,
tsconfigRootDir: rootDir,
project: './tsconfig.json',
},
parser: '@typescript-eslint/parser',
});

ruleTester.run('no-unsafe-unary-minus', rule, {
valid: [
'+42;',
'-42;',
'-42n;',
'(a: number) => -a;',
JoshuaKGoldberg marked this conversation as resolved.
Show resolved Hide resolved
'(a: bigint) => -a;',
'(a: number | bigint) => -a;',
'(a: any) => -a;',
'(a: 1 | 2) => -a;',
],
samestep marked this conversation as resolved.
Show resolved Hide resolved
invalid: [
{ code: '(a: string) => -a;', errors: [{ messageId: 'unaryMinus' }] },
{ code: '(a: {}) => -a;', errors: [{ messageId: 'unaryMinus' }] },
],
});

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.