我在JavaScript中有一个无法渲染的组件,我试图将其转换为TypeScript。我在声明render
版组件中的Vue.extend
函数时遇到错误:
(method) ComponentOptions<Vue, unknown, unknown, unknown, never[], Record<never, any>>.render?(createElement: CreateElement, hack: RenderContext<Record<never, any>>): VNode
No overload matches this call.
The last overload gave the following error.
Argument of type '{ render(): void; }' is not assignable to parameter of type 'ComponentOptions<Vue, DefaultData<Vue>, DefaultMethods<Vue>, DefaultComputed, PropsDefinition<Record<string, any>>, Record<string, any>>'.
Types of property 'render' are incompatible.
Type '() => void' is not assignable to type '(createElement: CreateElement, hack: RenderContext<Record<string, any>>) => VNode'.
Type 'void' is not assignable to type 'VNode'.ts(2769)
vue.d.ts(90, 3): The last overload is declared here.
这是我要在TypeScript中尝试做的一个例子:
import Vue from 'vue'
export default Vue.extend({
render() { // error happens when I add this. I tried typing the render with :VNode
// and returning this.$scopedSlots.default({}), but error still occurs
}
})
我该如何解决?
答案 0 :(得分:0)
render()
具有以下签名:
render?(createElement: CreateElement, hack: RenderContext<Props>): VNode;
render()
声明的注意事项:
hack
不需要在您的代码中声明VNode
(即单个根节点),但Vue实际上接受VNode[]
作为返回值(this.$scopedSlots.default()
返回的内容) 解决方案1::将返回类型指定为VNode
,并返回包裹this.$scopedSlots.default()
的单个节点:
import Vue, { VNode, CreateElement } from 'vue'
export default Vue.extend({
render(h: CreateElement): VNode {
return h('div', this.$scopedSlots.default!({}))
}
})
解决方案2:在any
上使用this.$scopedSlots.default()
类型断言来解决类型错误:
import Vue from 'vue'
export default Vue.extend({
render() {
// The container node is expected to provide a single root,
// so it's okay to return `VNode[]` as any.
return this.$scopedSlots.default!({}) as any
}
})