【问题标题】:Express Request .query.xyz as string | string[]快速请求 .query.xyz 作为字符串 |细绳[]
【发布时间】:2020-05-26 16:16:52
【问题描述】:

我正在尝试为我的变量分配一个类型,该类型从 express 的请求查询中获取其值。 req.query 的类型为“QueryString.ParsedQs” 例如 req.query.accountId 的类型为“string | QueryString.ParsedQs | string[] | QueryString.ParsedQs[]”

如何从 req.query.accountId 中提取值,使其始终为字符串类型?

示例代码:

import { Request, Response } from "@feathersjs/express";
class Xyz {
    public myMethod( req: Request, res: Response ){
        const accountId =req.query.accountId;/* type is "string | QueryString.ParsedQs | string[] | QueryString.ParsedQs[]"*/
    }
}

【问题讨论】:

  • req.query.accountId as string?
  • 是的,我想将 accountId 传递给只接受字符串的函数。光说它“作为字符串”,会不会变成字符串?
  • 嗯,我的意思是它应该可以工作,只要它不是 ParsedQs,我不确定什么时候会发生。谢谢!

标签: typescript express request


【解决方案1】:

您可以检查 ‛string‛ 是否通过:

if (typeof accounId === 'string')  {
  // do stuff
}

或者将它(强制,我不推荐)转换为字符串:

accountId = String(req.query.accountId);
// Or shorter
accountId = '' + req.query.accountId;

如果在转换之前它不是一个字符串,你最终会得到类似 ‛[Object array]‛

【讨论】:

    猜你喜欢
    • 2023-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 2011-03-11
    相关资源
    最近更新 更多