[英]Vue/Typescript: how to type an object literal that returns css?
I am following the answer here ( Vue is it possible to use a prop for styling? (SCSS/ SASS) ) on how to use props in my css.我在这里关注答案( Vue is it possible to use a prop for style? (SCSS/SASS) )关于如何在我的 css 中使用道具。 I want to pass in
initWidth
as a prop but it has a default set to 300
.我想将
initWidth
作为道具传递,但它的默认设置为300
。 I am then setting an initial data to equal that prop so that a computed property can access it.然后我将初始数据设置为等于该道具,以便计算属性可以访问它。 I am getting a typescript error though
Property 'baseWidth' does not exist on type '{ cssProps(): void; }'.
我收到一个打字稿错误,尽管
Property 'baseWidth' does not exist on type '{ cssProps(): void; }'.
Property 'baseWidth' does not exist on type '{ cssProps(): void; }'.
. . Would I need to make a new interface for this?
我需要为此创建一个新界面吗?
props: {
initWidth: {
type: Number,
default: 300,
}
},
data() {
return {
baseWidth: this.initWidth
}
},
computed: {
cssProps() {
return {
'--baseWidth': this.baseWidth + "px",
}
}
}
TypeScript support for the Options API has a known limitation that requires annotating return types on computed
:对 Options API 的 TypeScript 支持有一个已知限制,需要在
computed
上注释返回类型:
Because of the circular nature of Vue's declaration files, TypeScript may have difficulties inferring the types of certain methods.
由于 Vue 声明文件的循环性质,TypeScript 可能难以推断某些方法的类型。 For this reason, you may need to annotate the return type on methods like
render
and those incomputed
.出于这个原因,您可能需要在
render
和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.由于
cssProps()
在其返回类型上没有注释,因此组件的类型推断被破坏,并且 TypeScript 不会将this.baseWidth
识别为数据属性。
You could solve the problem by annotating the return type of cssProps()
as Record<string,string>
:您可以通过将
cssProps()
的返回类型注释为Record<string,string>
来解决问题:
import Vue from 'vue'
export default Vue.extend({
computed: { 👇
cssProps(): Record<string, string> {
return { /*...*/ }
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.