no-unnecessary-type-assertion.js
10.4 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const experimental_utils_1 = require("@typescript-eslint/experimental-utils");
const tsutils_1 = require("tsutils");
const ts = __importStar(require("typescript"));
const util = __importStar(require("../util"));
exports.default = util.createRule({
name: 'no-unnecessary-type-assertion',
meta: {
docs: {
description: 'Warns if a type assertion does not change the type of an expression',
category: 'Best Practices',
recommended: 'error',
requiresTypeChecking: true,
},
fixable: 'code',
messages: {
unnecessaryAssertion: 'This assertion is unnecessary since it does not change the type of the expression.',
contextuallyUnnecessary: 'This assertion is unnecessary since the receiver accepts the original type of the expression.',
},
schema: [
{
type: 'object',
properties: {
typesToIgnore: {
type: 'array',
items: {
type: 'string',
},
},
},
},
],
type: 'suggestion',
},
defaultOptions: [{}],
create(context, [options]) {
const sourceCode = context.getSourceCode();
const parserServices = util.getParserServices(context);
const checker = parserServices.program.getTypeChecker();
const compilerOptions = parserServices.program.getCompilerOptions();
/**
* Sometimes tuple types don't have ObjectFlags.Tuple set, like when they're being matched against an inferred type.
* So, in addition, check if there are integer properties 0..n and no other numeric keys
*/
function couldBeTupleType(type) {
const properties = type.getProperties();
if (properties.length === 0) {
return false;
}
let i = 0;
for (; i < properties.length; ++i) {
const name = properties[i].name;
if (String(i) !== name) {
if (i === 0) {
// if there are no integer properties, this is not a tuple
return false;
}
break;
}
}
for (; i < properties.length; ++i) {
if (String(+properties[i].name) === properties[i].name) {
return false; // if there are any other numeric properties, this is not a tuple
}
}
return true;
}
/**
* Returns true if there's a chance the variable has been used before a value has been assigned to it
*/
function isPossiblyUsedBeforeAssigned(node) {
const declaration = util.getDeclaration(checker, node);
if (!declaration) {
// don't know what the declaration is for some reason, so just assume the worst
return true;
}
if (
// non-strict mode doesn't care about used before assigned errors
tsutils_1.isStrictCompilerOptionEnabled(compilerOptions, 'strictNullChecks') &&
// ignore class properties as they are compile time guarded
// also ignore function arguments as they can't be used before defined
tsutils_1.isVariableDeclaration(declaration) &&
// is it `const x!: number`
declaration.initializer === undefined &&
declaration.exclamationToken === undefined &&
declaration.type !== undefined) {
// check if the defined variable type has changed since assignment
const declarationType = checker.getTypeFromTypeNode(declaration.type);
const type = util.getConstrainedTypeAtLocation(checker, node);
if (declarationType === type) {
// possibly used before assigned, so just skip it
// better to false negative and skip it, than false positive and fix to compile erroring code
//
// no better way to figure this out right now
// https://github.com/Microsoft/TypeScript/issues/31124
return true;
}
}
return false;
}
function isConstAssertion(node) {
return (node.type === experimental_utils_1.AST_NODE_TYPES.TSTypeReference &&
node.typeName.type === experimental_utils_1.AST_NODE_TYPES.Identifier &&
node.typeName.name === 'const');
}
return {
TSNonNullExpression(node) {
const originalNode = parserServices.esTreeNodeToTSNodeMap.get(node);
const type = util.getConstrainedTypeAtLocation(checker, originalNode.expression);
if (!util.isNullableType(type)) {
if (isPossiblyUsedBeforeAssigned(originalNode.expression)) {
return;
}
context.report({
node,
messageId: 'unnecessaryAssertion',
fix(fixer) {
return fixer.removeRange([
originalNode.expression.end,
originalNode.end,
]);
},
});
}
else {
// we know it's a nullable type
// so figure out if the variable is used in a place that accepts nullable types
const contextualType = util.getContextualType(checker, originalNode);
if (contextualType) {
// in strict mode you can't assign null to undefined, so we have to make sure that
// the two types share a nullable type
const typeIncludesUndefined = util.isTypeFlagSet(type, ts.TypeFlags.Undefined);
const typeIncludesNull = util.isTypeFlagSet(type, ts.TypeFlags.Null);
const contextualTypeIncludesUndefined = util.isTypeFlagSet(contextualType, ts.TypeFlags.Undefined);
const contextualTypeIncludesNull = util.isTypeFlagSet(contextualType, ts.TypeFlags.Null);
// make sure that the parent accepts the same types
// i.e. assigning `string | null | undefined` to `string | undefined` is invalid
const isValidUndefined = typeIncludesUndefined
? contextualTypeIncludesUndefined
: true;
const isValidNull = typeIncludesNull
? contextualTypeIncludesNull
: true;
if (isValidUndefined && isValidNull) {
context.report({
node,
messageId: 'contextuallyUnnecessary',
fix(fixer) {
return fixer.removeRange([
originalNode.expression.end,
originalNode.end,
]);
},
});
}
}
}
},
'TSAsExpression, TSTypeAssertion'(node) {
var _a;
if (((_a = options.typesToIgnore) === null || _a === void 0 ? void 0 : _a.includes(sourceCode.getText(node.typeAnnotation))) ||
isConstAssertion(node.typeAnnotation)) {
return;
}
const originalNode = parserServices.esTreeNodeToTSNodeMap.get(node);
const castType = checker.getTypeAtLocation(originalNode);
if (tsutils_1.isTypeFlagSet(castType, ts.TypeFlags.Literal) ||
(tsutils_1.isObjectType(castType) &&
(tsutils_1.isObjectFlagSet(castType, ts.ObjectFlags.Tuple) ||
couldBeTupleType(castType)))) {
// It's not always safe to remove a cast to a literal type or tuple
// type, as those types are sometimes widened without the cast.
return;
}
const uncastType = checker.getTypeAtLocation(originalNode.expression);
if (uncastType === castType) {
context.report({
node,
messageId: 'unnecessaryAssertion',
fix(fixer) {
return originalNode.kind === ts.SyntaxKind.TypeAssertionExpression
? fixer.removeRange([
node.range[0],
node.expression.range[0] - 1,
])
: fixer.removeRange([
node.expression.range[1] + 1,
node.range[1],
]);
},
});
}
// TODO - add contextually unnecessary check for this
},
};
},
});
//# sourceMappingURL=no-unnecessary-type-assertion.js.map