ref with generic type #9564
-
Hi, I have difficulties trying to use a generic type with a <script setup lang="ts" generic="T">
import { ref } from 'vue';
const props = defineProps<{
foo: T
}>();
const myRef = ref<T | null>(null);
myRef.value = props.foo; // <- shouldn't this work?
</script> The last line produces this error:
I am not sure if I'm missing something, or if I encountered a bug. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
When working with a generic type, it's better to use the const myRef: Ref<T | null> = ref(null);
myRef.value = props.foo; The reason that this works is that, because of ref unwrapping, there is a difference between what goes into a ref function and what it returns as it's value. ref<T | null>() //=> resulting type: Ref<UnwrapRef<T>> |
Beta Was this translation helpful? Give feedback.
-
@LinusBorg why it doesn't work if I initialize the ref with the prop value? const myRef: Ref<T | null> = ref(props.foo); |
Beta Was this translation helpful? Give feedback.
When working with a generic type, it's better to use the
Ref
type than to pass a type argument toref<>()
. This works fine:playground
The reason that this works is that, because of ref unwrapping, there is a difference between what goes into a ref function and what it returns as it's value.