我有一个包含forwardRef的组件AddComment:

function AddComment({ comment, setComment }: Props, ref: Ref<HTMLDivElement>) {
  return (<div ref={ref}>
  // code...
  </div>)
}
export default forwardRef<HTMLDivElement>(AddComment)

在父零部件中:

function Parent() {
  const [comment, setComment] = useState('')
  const addCommentRef = useRef<HTMLDivElement>(null)

  return (<div>
  // code ...
    <AddComment ref={addCommentRef} comment={comment} setComment={setComment}/>
  </div>)
}

我得到了这个错误:

Argument of type '({ comment, setComment }: Props, ref: Ref<HTMLDivElement>) => Element' is not assignable to parameter of type 'ForwardRefRenderFunction<HTMLDivElement, {}>'.
  Types of parameters '__0' and 'props' are incompatible.
    Type '{}' is missing the following properties from type 'Props': comment, setComment

当我在浏览器上运行时,它运行得很好,但我在VS代码中出现了错误.

我怎么才能解决这个问题呢?

推荐答案

forwardRef是一个泛型函数,它具有用于引用和props 类型的类型参数.

将其更改为forwardRef<HTMLDivElement, Props>(AddComment)以包括Props类型.

阅读更多关于forwardRef in this article的内容

Typescript相关问答推荐

错误:note_modules/@types/note/globals.d.ts:72:13 -错误TS 2403:后续变量声明必须具有相同的类型

如何修复VueJS中的val类型不能赋给函数

如果我有对象的Typescript类型,如何使用其值的类型?

界面中这种类型的界面界面中的多态性

Angular 17 Select 错误core.mjs:6531错误错误:NG 05105:发现意外合成监听器@transformPanel.done

typescribe不能使用值来索引对象类型,该对象类型满足具有该值的另一个类型'

如何编写一个类型脚本函数,将一个对象映射(转换)为另一个对象并推断返回类型?

使用TypeScrip根据(可选)属性推断结果类型

如何在TypeScrip中正确键入元素和事件目标?

为什么在回调函数的参数中不使用类型保护?

如何在Type脚本中动态扩展函数的参数类型?

FatalError:Error TS6046:';--模块分辨率';选项的参数必须是:'; node ';,'; node 16';,'; node

如何从输入中删除值0

Rxjs将省略的可观测对象合并到一个数组中

为什么`map()`返回类型不能维护与输入相同数量的值?

窄SomeType与SomeType[]

Typescript泛型调用对象';s方法

如何在Vue动态类的上下文中解释错误TS2345?

通过辅助函数获取嵌套属性时保留类型

如何按成员资格排除或 Select 元组?