/
no-unsafe-unary-minus.ts
58 lines (55 loc) · 1.45 KB
/
no-unsafe-unary-minus.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import * as tsutils from 'ts-api-utils';
import * as ts from 'typescript';
import * as util from '../util';
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 = util.getConstrainedTypeAtLocation(
services,
node.argument,
);
const checker = services.program.getTypeChecker();
if (
tsutils
.unionTypeParts(argType)
.some(
type =>
!tsutils.isTypeFlagSet(
type,
ts.TypeFlags.Any |
ts.TypeFlags.Never |
ts.TypeFlags.BigIntLike |
ts.TypeFlags.NumberLike,
),
)
) {
context.report({
messageId: 'unaryMinus',
node,
data: { type: checker.typeToString(argType) },
});
}
},
};
},
});