【问题标题】:How to convert Expressjs Arrow Function from JavaScript to TypeScript如何将 Expressjs 箭头函数从 JavaScript 转换为 TypeScript
【发布时间】:2021-12-13 12:02:15
【问题描述】:

我正在将 Expressjs 项目从 JavaScript 转换为 TypeScript。

初始 JavaScript 模块catchAsyncError.js

module.exports = theFunc => (req, res, next) => {
    Promise.resolve(theFunc(req, res, next)).catch(next);
}

我尝试转换为 TypeScriptcatchAsyncError.ts

import { Request, Response, NextFunction} from "express";

const theFunc => (req: Request, res: Response, next: NextFunction) => {
    Promise.resolve(theFunc(req, res, next)).catch(next);
}
export default theFunc;

但是有一个错误:变量 'theFunc' 隐式具有 'any' 类型.ts(7005)

有人可以建议和解释吗?提前致谢。

【问题讨论】:

标签: node.js typescript express


【解决方案1】:

参考cmgchess给出的链接, Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

我设法隐藏了它:

catchAsyncError.ts

import { Request, Response, NextFunction} from "express";


const catchAsyncError = (theFunc: any) => (req: Request, res: Response, next: NextFunction) => {
    Promise.resolve(theFunc(req, res, next)).catch(next);
}

export default catchAsyncError;

感谢大家的宝贵时间!

【讨论】:

    【解决方案2】:

    我认为您需要在函数定义中将 => 替换为 =

    //   see here \/
    const theFunc = (req: Request, res: Response, next: NextFunction) => {
        Promise.resolve(theFunc(req, res, next)).catch(next);
    }
    

    【讨论】:

    • Dan P 还添加了返回类型 (:Promise)。可能应该是 Promise 因为它可能是隐含的 Promise ?
    • 我不是故意在那里添加 Promise,我的错!函数不需要返回值。
    • 您好 Dan P,您的代码没有给出错误,但似乎含义已更改
    猜你喜欢
    • 2017-12-06
    • 2020-03-07
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 2019-04-12
    相关资源
    最近更新 更多