Skip to content
This repository was archived by the owner on Mar 25, 2021. It is now read-only.

Commit c51e1bd

Browse files
calebeggajafff
authored andcommitted
Refine no-unnecessary-type-assertion rule to not flag necessary assertions (#3120)
* Refine no-unnecessary-type-assertion rule to not flag necessary assertions Type assertions prevent a type from being widened in a couple of situations, such as in an object literal or the inferred return type of a function. * Fix lint errors. * Use isObjectType to avoid cast
1 parent c657baa commit c51e1bd

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

src/rules/noUnnecessaryTypeAssertionRule.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
* limitations under the License.
1616
*/
1717

18+
import { isObjectFlagSet, isObjectType, isTypeFlagSet } from "tsutils";
1819
import * as ts from "typescript";
1920
import * as Lint from "../index";
2021

@@ -65,6 +66,15 @@ class Walker extends Lint.AbstractWalker<void> {
6566
return;
6667
}
6768

69+
if (node.kind !== ts.SyntaxKind.NonNullExpression &&
70+
(isTypeFlagSet(castType, ts.TypeFlags.Literal) ||
71+
isObjectType(castType) &&
72+
isObjectFlagSet(castType, ts.ObjectFlags.Tuple))) {
73+
// It's not always safe to remove a cast to a literal type or tuple
74+
// type, as those types are sometimes widened without the cast.
75+
return;
76+
}
77+
6878
const uncastType = this.checker.getTypeAtLocation(node.expression);
6979
if (uncastType === castType) {
7080
this.addFailureAtNode(node, Rule.FAILURE_STRING, node.kind === ts.SyntaxKind.TypeAssertionExpression

test/rules/no-unnecessary-type-assertion/test.ts.fix

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,3 +69,13 @@ function func(aOrB: TypeA|TypeB) {
6969
let z = aOrB;
7070
}
7171
}
72+
73+
// Expecting no warning for these assertions as they are not unnecessary.
74+
75+
type Bar = 'bar';
76+
const data = {
77+
x: 'foo' as 'foo',
78+
y: 'bar' as Bar,
79+
}
80+
81+
[1, 2, 3, 4, 5].map(x => [x, 'A' + x] as [number, string]);

test/rules/no-unnecessary-type-assertion/test.ts.lint

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,3 +86,13 @@ function func(aOrB: TypeA|TypeB) {
8686
~~~~~~~~~~~ [This assertion is unnecessary since it does not change the type of the expression.]
8787
}
8888
}
89+
90+
// Expecting no warning for these assertions as they are not unnecessary.
91+
92+
type Bar = 'bar';
93+
const data = {
94+
x: 'foo' as 'foo',
95+
y: 'bar' as Bar,
96+
}
97+
98+
[1, 2, 3, 4, 5].map(x => [x, 'A' + x] as [number, string]);

0 commit comments

Comments
 (0)