typescript 打字稿 | 关于缺少函数返回类型的警告,ESLint
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54814753/
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
Typescript | Warning about Missing Return Type of function, ESLint
提问by Dimitris Efst
I have a REACT-STATELESS-COMPONENT
, in a project with TypeScript. It has an error, saying, that
我有一个REACT-STATELESS-COMPONENT
, 在一个带有 TypeScript 的项目中。它有一个错误,说,
Missing return type on function.eslint(@typescript-eslint/explicit-function-return-type)
I am not sure what it wants me to do. Here is my code:
我不确定它想让我做什么。这是我的代码:
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;
Can you tell me what I need to do. I need to read about TS, but currently I don't get it at all. And I can't commit right now cause of this.
你能告诉我我需要做什么吗?我需要阅读有关 TS 的信息,但目前我根本不了解。由于这个原因,我现在无法承诺。
采纳答案by Nicholas Tower
I'd recommend using the types provided by react; they'll include the return type. If you're on the version 16.8.0 or later of react, do this:
我建议使用 react 提供的类型;他们将包括返回类型。如果您使用的是 16.8.0 或更高版本的 react,请执行以下操作:
const Component: React.FunctionComponent<Props> = (props) => (
Or use the shorthand:
或者使用简写:
const Component: React.FC<Props> = (props) => (
Prior to 16.8, you'd instead do:
在 16.8 之前,您应该这样做:
const Component: React.SFC<Props> = (props) => (
Where SFC stands for "stateless functional component". They changed the name, since function components are no longer necessarily stateless.
SFC 代表“无状态功能组件”。他们更改了名称,因为功能组件不再一定是无状态的。
回答by Robbie Milejczak
For a function return type it goes after the arguments:
对于函数返回类型,它位于参数之后:
({ prop }: Props & T): JSX.Element => {}
JSX.Element
is what TypeScript will infer, it's a pretty safe bet.
JSX.Element
是 TypeScript 会推断出的,这是一个非常安全的赌注。
If you're curious, you should be able to see what TypeScript infers as the return type by hovering over Component
, this will show the entire signature.
如果您好奇,您应该能够通过将鼠标悬停在 上来查看 TypeScript 推断出的返回类型Component
,这将显示整个签名。
回答by Softmixt
This is how I usually declare a component using typescript:
这就是我通常使用打字稿声明组件的方式:
import * as React from 'react';
type MyComponentProps = {
myStringProp: String,
myOtherStringProp: String
};
const MyComponent: React.FunctionComponent<MyComponentProps> = ({ myStringProp, myOtherStringProp }): JSX.Element => {
return (
<div>
<h1>This is My Component</h1>
</div>
);
};
export default MyComponent;