反应:缺少函数的返回类型。eslint(@typescript-eslint/explicit-function-return-type)

Ser*_*ioP 12 typescript reactjs eslint

我是 Typescript React 的新手。在一个非常基本的功能组件中,eslint 抱怨我它缺少功能组件本身的返回类型。我错在哪里?

在此处输入图片说明

小智 18

正如 Nicholas Tower 在这个答案中所解释的那样Typescript | 关于缺少函数返回类型 ESLint 的警告,根据您使用的React版本,您可以使用以下任何行:

如果您使用的是最新的 React 版本(16.8.0 或更高版本),请执行以下操作: const Component: React.FunctionComponent<Props> = (props: Props) => (

在 16.8 之前,您应该这样做: const Component: React.SFC<Props> = (props: Props) => (

SFC 代表“无状态功能组件”。

编辑: - - -

根据@SergioP 的评论,更惯用的解决方案是

const Test = ({ title }: Props): JSX.Element => <div>{title}</div>

  • 使用这种语法,linter 不会抱怨:`const Test = ({ title }: Props): JSX.Element =&gt; &lt;div&gt;{title}&lt;/div&gt;` (18认同)

Rao*_*Rao 7

我也面临这个问题。

const handleLogout = () => {
router.push('/')
} 
Run Code Online (Sandbox Code Playgroud)

上面的代码给了我同样的问题,然后代码更新如下,然后错误在我的情况下消失

const handleLogout = (): void => {
router.push('/')
}
Run Code Online (Sandbox Code Playgroud)

参考链接: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/explicit-function-return-type.md