Dim*_*fst 7 javascript types typescript reactjs eslint
我REACT-STATELESS-COMPONENT在带有TypeScript的项目中有一个。它有一个错误,说,
Missing return type on function.eslint(@typescript-eslint/explicit-function-return-type)
Run Code Online (Sandbox Code Playgroud)
我不确定它要我做什么。这是我的代码:
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;
Run Code Online (Sandbox Code Playgroud)
你能告诉我我需要做什么。我需要阅读有关TS的信息,但目前我根本不了解它。我现在不能这样做。
Yan*_*ich 15
如果您使用@types/react,则不必为React组件提供返回类型。您可以像这样对 React 组件禁用此规则。只需将其添加到您的 .eslintrc.js 中:
overrides: [
{
files: ['*.jsx', '*.tsx'],
rules: {
'@typescript-eslint/explicit-module-boundary-types': ['off'],
},
},
],
Run Code Online (Sandbox Code Playgroud)
Sof*_*ixt 10
这就是我通常使用打字稿声明组件的方式:
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;
Run Code Online (Sandbox Code Playgroud)
我建议使用react提供的类型;它们将包含返回类型。如果您使用的是最新的React版本(16.8.0或更高版本),请执行以下操作:
const Component: React.FunctionComponent<Props> = (props: Props) => (
Run Code Online (Sandbox Code Playgroud)
在16.8之前,您可以:
const Component: React.SFC<Props> = (props: Props) => (
Run Code Online (Sandbox Code Playgroud)
SFC代表“无状态功能组件”。他们更改了名称,因为功能组件不再必须是无状态的。
对于函数返回类型,它放在参数之后:
({ prop }: Props & T): JSX.Element => {}
Run Code Online (Sandbox Code Playgroud)
JSX.Element 是TypeScript的推断,这是一个非常安全的选择。
如果您很好奇,则可以将鼠标悬停在上方Component,以查看TypeScript推断为返回类型的内容,这将显示整个签名。