eslint-plugin-vue
eslint-plugin-vue copied to clipboard
Rule Proposal: Validate "emits" section
Please describe what the rule should do:
This rule proposal is based on this issue: https://github.com/vuejs/core/issues/5343
It should ensure that emits section does not break vue component typing.
What category should the rule belong to?
Warns about a potential error (problem)
Provide 2-3 code examples that this rule should warn about:
Valid:
export default defineComponent({
name: "Sample",
emits: {
event1(this: undefined): boolean { return true; },
event2: (): boolean => { return true; },
event3: function(this: undefined): boolean { … }
},
Invalid:
export default defineComponent({
name: "Sample",
emits: {
event(): boolean { return true; },
event: function(): boolean { … }
},
Makes sense. I'd suggest vue/prefer-emits-arrow-function as a rule name. Arrow functions work in both TypeScript and JavaScript, and the preview docs section linked here recommend using them. So I wouldn't bother with the first style (event1(this: undefined) …).
So I wouldn't bother with the first style (event1(this: undefined) …).
The first notation (event1(this: undefined)) can be useful to avoid conflict with ESLint core rule object-shorthand. So, I would keep it.
Makes sense. I think the rule should indeed be called vue/prefer-emits-arrow-function and work like this:
Don't report arrow functions or functions (shorthand or longhand) with an explicit this parameter typed to undefined. Report all other functions (shorthand or longhand).
For an autofix, first detect if there is already type information (either only look at the function return type, or detect TypeScript usage in general somehow).
- If there isn't, provide an autofix to turn it into an arrow function. We can't be compatible with the
object-shorthandrule then. - If there is, don't provide an autofix, but two suggestions:
- Turn into arrow function
- Add explicit
undefinedtype forthisparameter
I guess that event: function(): boolean { … } will also be invalid? EDIT: Yes it is.
I guess that event: function(): boolean { … } will also be invalid?
I tried to use this pattern and it also breaks emit typing:
So, I guess it should also be reported.
But note that the pattern bellow works well (i.e. no need to report it):
event: function(this: undefined): boolean { … }
Thanks for checking.
But note that the pattern bellow works well (i.e. no need to report it):
Sure. That means that shorthand and longhand functions can be handled exactly the same. So the algorithm in my comment above should be fine.