skip to Main Content

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


  1. The answer is that you can’t use Cars into your v-model of test1 that only accepts Car. Because Cars could be Car2, and Car2 does not fit into Car.
    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:

    const useTest1 = computed(() => Math.random() > 0.5)
    const modelCar1 = ref({} as Car)
    const modelCar2 = ref({} as Car2)
    const component = computed(() => useTest1.value ? test1 : test2)
    // and then switch model depending on what component is
    

    Btw, make sure to put your type definitions into a separate file.

    Login or Signup to reply.
  2. Agree with Tobias about the cause (test1 and test2 don’t take Cars, but either Car or Car2), although I would propose different solutions:

    • unify your interface on test1/test2 (probably not what you want)
    • if you v-if/v-else your components in the template instead of making it a computed (e.g. through checking the existence of one of the properties), TS will apply correct type narrowing of the v-modeled type
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search