函数上缺少返回类型-在React(TypeScript)代码中

时间:2019-05-08 13:10:00

标签: reactjs typescript eslint prettier

在我的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)上缺少返回类型

我正在使用带有TypeScript的React。 对于短绒毛衫,我使用ESLint,并且对Prettier进行代码格式化。

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

App.tsc

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>
        );
    }
}

Component1.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' }),
    };
};

减速器和动作位于单独的文件夹中。

Component1和Component2是相似的。

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

1 个答案:

答案 0 :(得分:1)

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

可访问性修饰符是公共/私有/受保护的。对于渲染,它应该是公开的。

因此将public一词添加到render():

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/redux作为您的redux代码:(npm i -D @types/redux)     从'redux'导入{Dispatch};

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

相关问题