Javascript Typescript |关于缺少函数返回类型的警告,ESLint

Javascript Typescript |关于缺少函数返回类型的警告,ESLint,javascript,reactjs,typescript,types,eslint,Javascript,Reactjs,Typescript,Types,Eslint,我有一个REACT-STATELESS-COMPONENT,在一个带有TypeScript的项目中。它有一个错误,说 Missing return type on function.eslint(@typescript-eslint/explicit-function-return-type) 我不知道它要我做什么。这是我的密码: import React, { Fragment} from 'react'; import IProp from 'dto/IProp'; export int

我有一个
REACT-STATELESS-COMPONENT
,在一个带有TypeScript的项目中。它有一个错误,说

Missing return type on function.eslint(@typescript-eslint/explicit-function-return-type)
我不知道它要我做什么。这是我的密码:

import React, { Fragment} from 'react';
import IProp from 'dto/IProp';

export interface Props {
  prop?: IProp;
}

const Component = <T extends object>({ prop }: Props & T) => (
  <Fragment>
    {prop? (
      <Fragment>
        Some Component content..
      </Fragment>
    ) : null}
  </Fragment>
);

LicenseInfo.defaultProps: {};

export default Component;

import React,{Fragment}来自'React';
从“dto/IProp”导入IProp;
导出接口道具{
项目?:IProp;
}
常量组件=({prop}:Props&T)=>(
{道具(
一些组件内容。。
):null}
);
LicenseInfo.defaultProps:{};
导出默认组件;

你能告诉我我需要做什么吗。我需要了解TS,但目前我一点也不了解。由于这个原因,我现在无法提交。

我建议使用react提供的类型;它们将包括返回类型。如果您使用的是react的16.8.0或更高版本,请执行以下操作:

const Component: React.FunctionComponent<Props> = (props) => (
const组件:React.FunctionComponent=(props)=>(
或使用速记:

const Component: React.FC<Props> = (props) => (
const组件:React.FC=(道具)=>(
在16.8之前,您应该执行以下操作:

const Component: React.SFC<Props> = (props) => (
const组件:React.SFC=(props)=>(

其中SFC代表“无状态功能组件”。他们更改了名称,因为功能组件不再一定是无状态的。

对于函数返回类型,它在参数后面:

({ prop }: Props & T): JSX.Element => {}
JSX.Element
是TypeScript将推断的,这是一个相当安全的赌注


如果您感到好奇,您应该能够通过将鼠标悬停在
组件上,看到TypeScript推断的返回类型,这将显示整个签名。

这是我通常使用TypeScript声明组件的方式:

import*as React from'React';
类型MyComponentProps={
myStringProp:String,
myOtherStringProp:String
};
const MyComponent:React.FunctionComponent=({myStringProp,myOtherStringProp}):JSX.Element=>{
返回(
这是我的组件
);
};
导出默认MyComponent;

谢谢。这实际上用defaultProps修复了我的第二个组件。一个问题只是为了澄清问题。为什么在第二个组件中,我有defaultProps,下面的答案不起作用?我的意思是当你有
defaultProps
时有什么不同?我猜唯一明显的区别是它们各自的类型定义
React.SFC
在其定义中不包含
defaultProps
,而
JSX.Element
包含。错误消息是什么?@KenGregory
React.React.Element
对我有效,谢谢你的推荐!这对我不起作用:
const-HeaderNotification:React.FunctionComponent=(props:props)=>{
我仍然收到lambda函数的错误,因为它没有显式的返回类型。有什么方法可以修复吗?编辑:唯一有效的方法是:
const HeaderNotification:React.FunctionComponent=(props:props):JSX.Element=>{
无需显式键入
props
参数,因为它已经在泛型中键入了,所以这很好:
const-Component:React.FunctionComponent=(props)=>(
更好的方法是分解prop对象:
const-Component:React.FunctionComponent=({prop})=>(
也许,您的评论可能已经过时,因为有一个关于这个主题的新讨论。他们建议将
React.FC
替换为
JSX.Element
。Typescript应该能够推断React组件的返回类型。这应该是不必要的。