首页 > 解决方案 > Vue / Typescript:如何键入返回css的对象文字?

问题描述

我在这里关注答案(Vue is it possible to use a prop for style? (SCSS/SASS))关于如何在我的 css 中使用道具。我想initWidth作为道具传入,但它的默认设置为300. 然后我将初始数据设置为等于该道具,以便计算属性可以访问它。我收到打字稿错误Property 'baseWidth' does not exist on type '{ cssProps(): void; }'.。我需要为此创建一个新界面吗?

props: {
   initWidth: {
       type: Number,
       default: 300,
   }
},

data() {
    return {
       baseWidth: this.initWidth
    }
},

computed: {
    cssProps() {
       return {
           '--baseWidth': this.baseWidth + "px",
       }
    }
}

标签: typescriptvue.js

解决方案


对 Options API 的 TypeScript 支持有一个已知限制,需要在以下位置注释返回类型computed

由于 Vue 声明文件的循环性质,TypeScript 可能难以推断某些方法的类型。出于这个原因,您可能需要在方法上注释返回类型,render例如computed.

由于cssProps()在其返回类型上没有注释,因此组件的类型推断被破坏,并且 TypeScript 无法识别this.baseWidth为数据属性。

cssProps()您可以通过将返回类型注释为as来解决问题Record<string,string>

import Vue from 'vue'

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

推荐阅读