node.js - 为什么 request.query 不再是 'any' 了? express request.query typescript 错误

标签 node.js typescript express

在 npm i 之后,这是我尝试将查询参数传递给需要字符串的函数时得到的错误:
'string | 类型的参数查询 | (string | Query)[]' 不能分配给 'string' 类型的参数。
类型 'Query' 不可分配给类型 'string'.ts(2345)

import express from "express";
async function getProductsImagesByShopEvent(req: express.Request, res: express.Response, 
next: express.NextFunction) {
  try {
    const params = req.query;
    if (!params || !params.shopEventId)
        throw new CustomError("params are missing in /business/getProductsImagesByShopEvent", 400, "params are missing");

    const shopEvent = new ShopEvent();
    const events = await shopEvent.getProductsImagesByShopEvent(params.shopEventId);
    res.json(events);
  }
  catch (error) {
    next(error);
  }
}

async getProductsImagesByShopEvent(shopEventId: string) {
}

错误在 params.shopEventId..
如果我添加: const params = (req.query as any);有用

最佳答案

这使得 express 在类型上更加严格。您必须添加类型。

const shopEventId: string = req.query.shopEventId as string

关于node.js - 为什么 request.query 不再是 'any' 了? express request.query typescript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61305362/

相关文章:

javascript - 当分配给 Angular 5 中的变量时,订阅外部未定义的值

typescript - 静态常量 : how?

node.js - 将 Mocha Chai 与 Stormpath 结合使用

javascript - 使用 forEach() 返回数组值

angular - 从映射生成类型/接口(interface)列表

html - 使用查询字符串表达 res.sendFile()

node.js - Express/Node 依赖项的模式 : Can I use a separate services file for "app" instance?

javascript - Node.js 上的异步问题

javascript - 错误: concatUint8Array: Data must be in the form of a Uint8Array

node.js - 使用 Digital Ocean 和 FlightPlan.js 时 Node 应用程序出错 - 所有配置的身份验证方法均失败