eslint-plugin-vue icon indicating copy to clipboard operation
eslint-plugin-vue copied to clipboard

`MaybeRef`s should be used with `unref`

Open jhoermann opened this issue 1 year ago • 2 comments

Please describe what the rule should do: Currently using a MaybeRef without using unref wouldn't lead to an eslint error:

const maybeRef: MaybeRef<boolean> = ref(false)
if (maybeRef) { // would be always true in this case but not catched with @typescript-eslint/no-unnecessary-condition
    ...
}

It should be enforced using unref in this case to prevent false positives in conditions.
Name of rule tbd.

What category should the rule belong to? [ ] Enforces code style (layout) [x] Warns about a potential error (problem) [ ] Suggests an alternate way of doing something (suggestion) [ ] Other (please specify:)

jhoermann avatar Nov 21 '24 10:11 jhoermann

This would require type information, so it would only be possible when typescript-eslint's parser is used.

Other patterns that should be reported:

(maybeRef ? x : y)
!maybeRef

maybeRef || x
maybeRef && y
maybeRef ?? x

x || maybeRef
x && maybeRef
x ?? maybeRef

maybeRef == x
maybeRef != x
maybeRef === x
maybeRef !== x

x == maybeRef
x != maybeRef
x === maybeRef
x !== maybeRef

Boolean(maybeRef)
String(maybeRef)

As a name, I'd suggest vue/require-mayberef-unwrap

Similar to

  • #2140
  • https://eslint.vuejs.org/rules/no-ref-as-operand.html

FloEdelmann avatar Nov 21 '24 10:11 FloEdelmann

I am planning to create a PR for this new rule proposition 😁

Should vue/require-mayberef-unwrap also flag variables typed as MaybeRef<T> / MaybeRefOrGetter<T> even when they’re only annotated, not created via ref()/computed()?

2nofa11 avatar Jul 10 '25 13:07 2nofa11