typescript 如何修复绑定元素 'children' 隐式具有 'any' type.ts(7031)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/55370851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fix Binding element 'children' implicitly has an 'any' type.ts(7031)?
提问by Zahid Karim
I'm missing something here with the validation how to add types validation? Having error "element 'children' implicitly has an 'any' type".
我在这里缺少验证如何添加类型验证?出现错误“元素‘children’隐含具有‘any’类型”。
import * as React from 'react';
import Button from './Styles';
const Button1 = ({ children, ...props }) => (
<Button {...props}>{children}</Button>
);
Button1.propTypes = {};
export default Button1;
回答by Luká? Gibo Vaic
Yes you are missing a type for Props as whole, which means typescript sees it as any
and your ts rules dont allow it.
是的,您缺少整个 Props 的类型,这意味着 typescript 将其视为any
并且您的 ts 规则不允许它。
You have to type your props as:
你必须输入你的道具:
interface IProps {
children: ReactNode;
// any other props that come into the component
}
const Button1 = ({ children, ...props }: IProps) => (
<Button {...props}>{children}</Button>
);
回答by Hung Ton
You can also add the predefined type to your functional components like this:
您还可以将预定义类型添加到您的功能组件中,如下所示:
const Button1: React.FC<{}> = ({ children }) => (
<Button>{children}</Button>
);
By this way you don't have to repeat yourself to define children
props.
通过这种方式,您不必重复自己来定义children
道具。
The fuller version could be like this:
更完整的版本可能是这样的:
interface Props {
// any other props that come into the component, you don't have to explicitly define children.
}
const Button: React.FC<Props> = ({ children, ...props }) => {
return (
<Button {...props}>{children}</Button>
);
};
Please note it works for React 16.8
请注意它适用于React 16.8
回答by Akshay Vijay Jain
This error can be fixed by explicitly defining type for the variable (children
in this case) and not leaving it to be implicitly inferred
可以通过显式定义变量的类型(children
在这种情况下)而不是隐式推断它来修复此错误
Error can be stopped altogether with TypeScript --noImplicitAny
compiler option
使用 TypeScript编译器选项可以完全停止错误--noImplicitAny