Arkandias
Arkandias

Reputation: 131

Type of Vue reference in a component with a generic type

I am using Vue 3 (Composition API) with Typescript. Here is my code.

<script setup lang="ts" generic="T">
import { ref, Ref } from "vue";

const props = defineProps<{
  myProp: T;
}>();

const model: Ref<T> = ref(props.myProp);
</script>

My IDE (WebStorm 2024.1.2 with Vue Language Server 1.8.27) tells me: "Vue: Type Ref<UnwrapRef<T>> is not assignable to type Ref<T>", "Type UnwrapRef<T> is not assignable to type T"

Final Edit: This line was indeed producing an error on build. I resolved this by using shallowRef (in my case, T has no nested fields anyway):

const model: ShallowRef<T> = shallowRef(props.getValue);

Another possibility, suggested in this issue, is to cast our ref as follows:

const model = ref<T>(props.getValue) as Ref<T>;

But this does not seem appropriate, because if type T has some nested refs, the type of model.value (that is UnwrapRef<T>) will not indeed be assignable to the type T. Moreover, ESLint still complains about the above piece of code: "ESLint: This assertion is unnecessary since it does not change the type of the expression.(@typescript-eslint/no-unnecessary-type-assertion)"

Upvotes: 1

Views: 508

Answers (0)

Related Questions