-
Notifications
You must be signed in to change notification settings - Fork 889
Refine no-unnecessary-type-assertion rule to not flag necessary assertions #3120
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -69,3 +69,13 @@ function func(aOrB: TypeA|TypeB) { | |
let z = aOrB; | ||
} | ||
} | ||
|
||
// Expecting no warning for these assertions as they are not unnecessary. | ||
|
||
type Bar = 'bar'; | ||
const data = { | ||
x: 'foo' as 'foo', | ||
y: 'bar' as Bar, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't get why you need this behavior. A type annotation would also work const data = {x: 'foo', y: Bar} = {x: 'foo', y: bar} Same goes for the arrow function below: just add the return type: [1, 2, 3, 4, 5].map((x): [number, string] => [x, 'A' + x]); I guess it's useful if the assertion is only a little part of a bigger object where you don't want to write the whole type? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's a relatively common pattern in our very large codebase where we're trying to turn on this rule. I don't think there's anything so wrong with the pattern that it would make sense to ban it. It keeps you from having to repeat the keys, at least. Skimming through my list of breakages, I also see: const FOO = {
bar: 'a' as 'a',
baz: 'stuff',
// ... many more properties without 'as' i.e., not all properties are cast like this. For those I would hate to have to make it so much more verbose. I also see instances of: for (const foo of ['bar' as 'bar', 'baz' as 'baz']) { /* ... */ } Also, a search turned up a match in tslint itself: There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. That makes sense, thank you for the detailed explanation |
||
} | ||
|
||
[1, 2, 3, 4, 5].map(x => [x, 'A' + x] as [number, string]); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
you can use
isObjectType(castType)
to avoid the assertion in the next lineThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done, thanks!