ComputedRef should not extend Ref, to prevent accidental writes to computed.value #12659
pietdevries94
started this conversation in
Ideas
Replies: 1 comment
-
If you are using vueuse, you get some utility types out of the box that match your issue: /**
* Maybe it's a ref, or a plain value.
*/
type MaybeRef<T = any> = T | Ref<T> | ShallowRef<T> | WritableComputedRef<T>;
/**
* Maybe it's a ref, or a plain value, or a getter function.
*/
type MaybeRefOrGetter<T = any> = MaybeRef<T> | ComputedRef<T> | (() => T);
/**
* Maybe it's a computed ref, or a readonly value, or a getter function
*/
type ReadonlyRefOrGetter<T> = ComputedRef<T> | (() => T); Interesting to know what's the vue team opinion on this. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Currently, we can pass
ComputedRef
to a function that requiresRef
, losing the type check that a computed ref can't be written to.Example:
Of course the example is a bit nonsensical, but it demonstrates how easy it is to loose type safety. And it's not an uncommon practice to pass refs to external functions.
To make matters more complicated, there is no type that encompasses both
ComputedRef
andRef
in a read-only matter, except currentlyReadonly<Ref<T>>
.My suggestion is to have a base type that is readonly by default and supports both computed and ref, and an explicit writable type that supports
WritableComputed
andRef
.I'm probably missing a bunch of cases, but I believe this is a good starting point for discussion.
Beta Was this translation helpful? Give feedback.
All reactions