Search code examples
javascripttypescriptvue.jsvue-composition-api

Dealing with Typescript Vue component uninitialized reactive object


In a composition API Vue 3 component, I'm using reactive objects that'll be populated asynchronously with external data.
I'm using "nullable" {} object for that purpose:

import { Ref, ref } from 'vue'
import { Car } from '@mytypes/vehicules'

const car: Ref<Car|{}> = ref({})

fetch('/cars/42').then((result: Car) => {
  car.value = result
}

So I can show potentially empty data on the template

<h1>{{ car.model }}</h1>
<label>Brand</label> {{ car.brand }}
<label>Engine</label> {{ car.engine }}
<label>Color</label> {{ car.color }}

It seems to me like a dirty hack and each time I do that, I'm facing the issue that I need to chain declare Car|{} everywhere the value is propagated to keep Typescript happy enough.

I imagine there is a much proper way to do that, isn't it ?


Solution

  • I would define the reference as nullable:

    const car: Ref<Car | null> = ref(null);
    

    And then use the optional chaining operator in my template:

    <h1>{{ car?.model }}</h1>