如何修复绑定元素'children'隐式具有'any' type.ts(7031)?

新手上路,请多包涵

我在这里遗漏了一些关于如何添加类型验证的验证?出现错误“元素‘子’隐含地具有‘任何’类型”。

 import * as React from 'react';
import Button from './Styles';

const Button1 = ({ children, ...props }) => (
  <Button {...props}>{children}</Button>
);

Button1.propTypes = {};

export default Button1;

原文由 Zahid Karim 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 3.3k
2 个回答

编辑 2022:使用 react 18,FC 不再提供子项,因此您必须自己输入,并且可以删除 FC:

 import React, { ReactNode } from "react";

interface Props {
    children?: ReactNode
    // any props that come into the component
}

const Button1 = ({ children, ...props }: Props) => (
    <Button {...props}>{children}</Button>
);

是的,您缺少整个 Props 的类型,这意味着打字稿将其视为 any 并且您的 ts 规则不允许这样做。

您必须将道具键入为:

 import React, { FC } from "react";

interface Props {
    // any props that come into the component
}

const Button1: FC<Props> = ({ children, ...props }) => (
    <Button {...props}>{children}</Button>
);

原文由 Lukáš Gibo Vaic 发布,翻译遵循 CC BY-SA 4.0 许可协议

这对我来说是一个主要问题,我浪费了很多时间来找出正确的解决方案。现在你的 children 道具有一个错误,但在未来,你可能会在许多你正在解构参数的函数中遇到这个错误。所以我建议,关注这个 GitHub 问题

 const yourfunc = ({destructuredProps}: {destructuredProps: type}) => {}

原文由 MANAN 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进