5

我在 JavaScript 中有一个无渲染组件,我正在尝试将其转换为 TypeScript。我在-ed 组件中声明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
  }
})

我该如何解决?

4

1 回答 1

7

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
  }
})
于 2019-09-22T09:00:42.563 回答