[Vuejs]-Vue/Typescript: how to type an object literal that returns css?

0👍

TypeScript support for the Options API has a known limitation that requires annotating return types on computed:

Because of the circular nature of Vue’s declaration files, TypeScript may have difficulties inferring the types of certain methods. For this reason, you may need to annotate the return type on methods like render and those in computed.

Since cssProps() has no annotation on its return type, the type inference for the component is broken, and TypeScript doesn’t recognize this.baseWidth as a data property.

You could solve the problem by annotating the return type of cssProps() as Record<string,string>:

import Vue from 'vue'

export default Vue.extend({
  computed: {           👇
    cssProps(): Record<string, string> {
      return { /*...*/ }
    }
  }
})

Leave a comment