网站搜索

typescript - Express Request .query.xyz 作为 string | string[]


我正在尝试为我的变量分配一个类型,该变量的值来自 express 的 Request query。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[]"*/
    }
}

答案#1

你可以检查是否传递了一个‘字符串’:

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

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

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

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