繁体   English   中英

打字稿 | 关于缺少函数返回类型的警告,ESLint

[英]Typescript | Warning about Missing Return Type of function, ESLint

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

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;

你能告诉我我需要做什么吗? 我需要阅读有关 TS 的信息,但目前我根本不了解。 由于这个原因,我现在无法承诺。

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

const Component: React.FunctionComponent<Props> = (props) => (

或者使用简写:

const Component: React.FC<Props> = (props) => (

在 16.8 之前,您应该这样做:

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

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

对于函数返回类型,它位于参数之后:

({ prop }: Props & T): JSX.Element => {}

JSX.Element是 TypeScript 会推断的,这是一个非常安全的赌注。

如果您很好奇,您应该能够通过将鼠标悬停在Component上来查看 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;

如果您使用 @types/react,则不必为 React 组件提供返回类型。 您可以为这样的反应组件禁用此规则。 只需将其添加到您的 .eslintrc.js 中:

  overrides: [
    {
      files: ['*.jsx', '*.tsx'],
      rules: {
        '@typescript-eslint/explicit-module-boundary-types': ['off'],
      },
    },
  ],

此规则旨在确保从函数返回的值是预期的类型。

以下模式被视为警告:

问题 :

// Should indicate that no value is returned (void)
function test() {
   return;
}

 // Should indicate that a number is returned
 var fn = function () {
   return 1;
 };

 // Should indicate that a string is returned
 var arrowFn = () => 'test';

 class Test {
   // Should indicate that no value is returned (void)
   method() {
     return;
  }
}

解决方案 :

// No return value should be expected (void)
function test(): void {
  return;
}

// A return value of type number
 var fn = function (): number {
  return 1;
};

// A return value of type string
var arrowFn = (): string => 'test';

class Test {
  // No return value should be expected (void)
  method(): void {
    return;
  }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM