forked from typescript-eslint/typescript-eslint
/
no-unnecessary-type-assertion.ts
293 lines (270 loc) · 9.39 KB
/
no-unnecessary-type-assertion.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
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import {
TSESTree,
AST_NODE_TYPES,
ESLintUtils,
} from '@typescript-eslint/experimental-utils';
import {
isObjectType,
isObjectFlagSet,
isStrictCompilerOptionEnabled,
isTypeFlagSet,
isVariableDeclaration,
} from 'tsutils';
import * as ts from 'typescript';
import * as util from '../util';
type Options = [
{
typesToIgnore?: string[];
},
];
type MessageIds = 'contextuallyUnnecessary' | 'unnecessaryAssertion';
export default util.createRule<Options, MessageIds>({
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: ts.ObjectType): boolean {
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: ts.Expression): boolean {
const declaration = ESLintUtils.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
isStrictCompilerOptionEnabled(compilerOptions, 'strictNullChecks') &&
// ignore class properties as they are compile time guarded
// also ignore function arguments as they can't be used before defined
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 = ESLintUtils.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: TSESTree.TypeNode): boolean {
return (
node.type === AST_NODE_TYPES.TSTypeReference &&
node.typeName.type === AST_NODE_TYPES.Identifier &&
node.typeName.name === 'const'
);
}
return {
TSNonNullExpression(node): void {
if (
node.parent?.type === AST_NODE_TYPES.AssignmentExpression &&
node.parent.operator === '='
) {
if (node.parent.left === node) {
context.report({
node,
messageId: 'contextuallyUnnecessary',
fix(fixer) {
return fixer.removeRange([
node.expression.range[1],
node.range[1],
]);
},
});
}
// for all other = assignments we ignore non-null checks
// this is because non-null assertions can change the type-flow of the code
// so whilst they might be unnecessary for the assignment - they are necessary
// for following code
return;
}
const originalNode = parserServices.esTreeNodeToTSNodeMap.get(node);
const type = ESLintUtils.getConstrainedTypeAtLocation(
checker,
originalNode.expression,
);
if (!ESLintUtils.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 = ESLintUtils.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 = ESLintUtils.isTypeFlagSet(
type,
ts.TypeFlags.Undefined,
);
const typeIncludesNull = ESLintUtils.isTypeFlagSet(
type,
ts.TypeFlags.Null,
);
const contextualTypeIncludesUndefined = ESLintUtils.isTypeFlagSet(
contextualType,
ts.TypeFlags.Undefined,
);
const contextualTypeIncludesNull = ESLintUtils.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: TSESTree.TSTypeAssertion | TSESTree.TSAsExpression,
): void {
if (
options.typesToIgnore?.includes(
sourceCode.getText(node.typeAnnotation),
) ||
isConstAssertion(node.typeAnnotation)
) {
return;
}
const originalNode = parserServices.esTreeNodeToTSNodeMap.get(node);
const castType = checker.getTypeAtLocation(originalNode);
if (
isTypeFlagSet(castType, ts.TypeFlags.Literal) ||
(isObjectType(castType) &&
(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) {
if (originalNode.kind === ts.SyntaxKind.TypeAssertionExpression) {
const closingAngleBracket = sourceCode.getTokenAfter(
node.typeAnnotation,
);
return closingAngleBracket?.value === '>'
? fixer.removeRange([
node.range[0],
closingAngleBracket.range[1],
])
: null;
}
return fixer.removeRange([
node.expression.range[1] + 1,
node.range[1],
]);
},
});
}
// TODO - add contextually unnecessary check for this
},
};
},
});