缺少函数的返回类型 - 在react(typescript)代码中

IT技术 reactjs typescript eslint prettier
2021-05-02 12:20:21

在我的 App.tsx 中,我得到了这个:

  • function.eslint(@typescript-eslint/explicit-function-return-type) 上缺少返回类型

在我的主要类组件中,我得到了这些:

  • 缺少方法定义上的可访问性修饰符 render.eslint(@typescript-eslint/explicit-member-accessibility)
  • function.eslint(@typescript-eslint/explicit-function-return-type) 上缺少返回类型

我正在将 React 与 TypeScript 一起使用。对于 linter,我使用 ESLint 和代码格式化 Prettier。

我找到了这个信息:https://github.com/typescript-eslint/typescript-eslint/blob/v1.6.0/packages/eslint-plugin/docs/rules/explicit-function-return-type.md,但我不不知道如何以及在哪里应用它。

应用程序

class Main extends Component {
    render() {
        return (
            <Router>
                <div>
                    <Link to="/">Home</Link>
                    <br />
                    <Link to="/component1">Component1</Link>
                    <br />
                    <Link to="/component2">Component2</Link>

                    <Route exact path="/" render={() => <h1>Home Page</h1>} />
                    <Route path="/component1" component={Component1} />
                    <Route path="/component2" component={Component2} />
                </div>
            </Router>
        );
    }
}

组件1.tsc

interface Props {
    number: number;
    onNumberUp: any;
    onNumberDown: any;
}

const Component1 = (props: Props): JSX.Element => {
    return (
        <div>
            <h1>Component1 content</h1>
            <p>Number: {props.number}</p>
            <button onClick={props.onNumberDown}>-</button>
            <button onClick={props.onNumberUp}>+</button>
        </div>
    );
};

const mapStateToProps = (state: any) => {
    return {
        number: state.firstReducer.number,
    };
};

const mapDispachToProps = (dispach: any) => {
    return {
        onNumberUp: () => dispach({ type: 'NUMBER_UP' }),
        onNumberDown: () => dispach({ type: 'NUMBER_DOWN' }),
    };
};

Reducer 和 actions 位于不同的文件夹中。

Component1 和 Component2 类似。

有人知道如何解决这个错误吗?

1个回答
Missing accessibility modifier on method definition render.eslint(@typescript-eslint/explicit-member-accessibility)

可访问性修饰符是诸如公共/私有/保护之类的东西。对于渲染,这应该是公开的。

所以在render()中添加public这个词:

class Main extends Component {
    public render() {
        ...
    }
}


Missing return type on function.eslint(@typescript-eslint/explicit-function-return-type)

你不应该在这里出现那个错误。这告诉你添加一个返回类型来渲染,但是因为你已经扩展了 React.Component 它应该能够从类型定义加载类型。

你在你的项目中添加了 @types/react 和 @types/react-dom 吗?

如果不, npm i -D @types/react @types/react-dom

看起来您还需要@types/reduxredux 代码: ( npm i -D @types/redux) import { Dispatch } from 'redux';

const mapDispatchToProps = (dispatch: Dispatch<any>) => {
    return {
        onNumberUp: () => dispatch({ type: 'NUMBER_UP' }),
        onNumberDown: () => dispatch({ type: 'NUMBER_DOWN' }),
    };
};

最后一点 - 我不喜欢 ESLint 中的公共/私人访问者规则。我只想禁用它。更多信息(第 1 点):https : //medium.com/@martin_hotell/10-typescript-pro-tips-patterns-with-or-without-react-5799488d6680