12
votes

Im playing along with the new Vue plugin for using composition API and TypeScript and there is something I'm not quite understanding.

How am I supposed to type computed properties?

import Vue from 'vue'
import { ref, computed, Ref } from '@vue/composition-api'

export default Vue.extend({
  setup(props, context) {

    const movieName:Ref<string> = ref('Relatos Salvajes')
    const country:Ref<string> = ref('Argentina')

    const nameAndCountry = computed(() => `The movie name is ${movieName.value} from ${country.value}`);

    return { movieName, country, nameAndCountry }
  }
})

In this simple example I'm declaring two refs and a computed property to join both. VSC is telling me that computed properties are returning ReadOnly type... But I can't make it work.

1
But I can't make it work - what exactly? From your code I'd expect the type to be inferred correctly. - Estus Flask
I mean, what type should I add to nameAndCountry const for it to be properly typed. Is it something that should we do in a TS app with computed values? - pegido
I expect it to be something like Ref<ReadOnly<string>>. You don’t need to add a type here, it’s inferred. Also no need for refs, they are unambiguously inferred as strings. Make sure TS is in strict mode so you’ll be warned when types are skipped where they are required. - Estus Flask

1 Answers

19
votes

There are two different types for that.

If your computed prop is readonly:

const nameAndCountry: ComputedRef<string> = computed((): string => `The movie name is ${movieName.value} from ${country.value}`);

if it has a setter method:

const nameAndCountry: WritableComputedRef<string> = computed({
  get(): string {
    return 'somestring'
  },
  set(newValue: string): void {
    // set something
  },
});