【问题标题】:why request.query is not 'any' anymore? express request.query typescript error为什么 request.query 不再是“任何”?表达 request.query 打字稿错误
【发布时间】:2020-08-01 22:42:34
【问题描述】:

在 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);它有效

【问题讨论】:

    标签: node.js typescript express


    【解决方案1】:

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

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

    【讨论】:

    • Express 已经提供了这些类型。以上只是告诉你认为更懂的编译器。应该检查类型,绝对不能强制转换。
    • 我很久以前就明白的事情是当你提交时:npm install on a repo(有 package.json - 所有 npm 包都更新到最新的次要版本
    猜你喜欢
    • 2018-06-19
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 2023-01-21
    • 1970-01-01
    • 2022-01-08
    • 2020-03-21
    • 2014-04-23
    相关资源
    最近更新 更多