I want to bind the value of apiRes to v-model, but typescript error occurred :
Here is the approximate code where I encountered the error.
How should I fix this?
Arguments of type { modelValue: Cars | undefined; } cannot be assigned to type NonNullable<(Partial<{}> & Omit<{ readonly modelValue?: Car | undefined; } & VNodeProps & AllowedComponentProps & ComponentCustomProps & Readonly<...> , never> & Record<...>) | (Partial<...> & ... 1 more ... & Record<...>)> & Parameters of Record<...>.
<template>
<div>
<component :is="component" v-model="apiRes" />
</div>
</template>
<script lang="ts" setup>
import test1 from './test1.vue'
import test2 from './test2.vue'
import { computed, ref } from 'vue'
export interface Car {
age: number
name: string
}
export interface Car2 {
door: string
cvt: string
}
type Cars = Car | Car2
const component = computed(() => {
const random = Math.random()
return random > 0.5 ? test1 : test2
})
const apiRes = ref<Cars>()
</script>
//test1
<template>
<div>{{ props }}</div>
</template>
<script setup lang="ts">
import type { Car } from './test.vue'
const props = defineModel<Car>()
</script>
//test2
<template>
<div>{{ props }}</div>
</template>
<script setup lang="ts">
import type { Car2 } from './test.vue'
const props = defineModel<Car2>()
</script>
If I change it to the following, the error disappears, but this might not be the correct solution.
const apiRes = ref({} as Car)
2
Answers
The answer is that you can’t use
Cars
into your v-model oftest1
that only acceptsCar
. BecauseCars
could beCar2
, andCar2
does not fit intoCar
.Vice-versa for
test2
.Using the union type does not do what you want here.
To propose you a different way of typing
apiRes
, I would need to know why you need these two components and where apiRes comes from.But this should fix your error:
Btw, make sure to put your type definitions into a separate file.
Agree with Tobias about the cause (test1 and test2 don’t take Cars, but either Car or Car2), although I would propose different solutions: