-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Description
Repro
interface T {}
return {} as T
{
"rules": {
"@typescript-eslint/consistent-type-assertions": [
"warn",
{
"assertionStyle": "as",
"objectLiteralTypeAssertions": "allow-as-parameter"
},
],
}
}
Feature Suggestion
This is a feature suggestion.
In general in our codebase, we want to enforce our preference for const x: T = {...}
over const x = {...} as T
. So this rule generally works pretty well, especially with the allow-as-parameter
option, but it would be great to make some additional exceptions.
The main exception I'm interested in adding is a new option that would allow the above code example (the return statement) to lint without warnings, something like:
objectLiteralTypeAssertions: "allow-as-return"
The motivation for this is that it allows you to avoid an intermediate variable, i.e. currently you'd have to do this if you want to use this rule with the above settings:
const tmp: T = {}
return tmp
Instead of just:
return {} as T
Pull Request
I created a pull request for this. It's currently just a proof of concept, because I'm not sure of the best way to add this option and preserve backward compatibility.
A naiive approach could be to add new string options like "allow-as-return" or "allow-as-parameter-or-return", but that seems messy. Maybe the best thing would be to allow objectLiteralTypeAssertions
to accept an array?:
objectLiteralTypeAssertions: ["allow-as-parameter", "allow-as-return"]
I assume it would need to be backward compatible so that this still works as well, but maybe this usage could be deprecated:
objectLiteralTypeAssertions: "allow-as-parameter"
In my PR, I just quickly added allowAsReturn
as a separate option, but that's probably not the best design, especially considering that there may be other similar situations in addition to parameters and return statements (see first comment below).
Versions
package | version |
---|---|
@typescript-eslint/eslint-plugin |
2.20.0 |
@typescript-eslint/parser |
2.20.0 |
TypeScript |
3.7.4 |
ESLint |
6.8.0 |
node |
12.11.1 |
npm |
6.11.3 |