"键入'字符串

编程入门 行业动态 更新时间:2024-10-28 05:24:09
本文介绍了"键入'字符串 |string[]' 不可分配给类型 'string'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用 node + typescript 和集成的 swagger 进行 API 调用.我大摇大摆地提出以下要求

I am using node + typescript and integrated swagger for API Calls. I have a following request in swagger

localhost:3033/employees/search/?username=test

这里我要查找 username = test 的记录.

所以我使用 URL 模块解析查询字符串,如下所示,我在控制台中获取用户名.

So I parse the query string using URL module, like below and I am getting the username in my console.

var params = URL.parse(req.url, true).query; console.log(params); //gives me [Object: null prototype] { username: 'test' } in my console

但每当我尝试将 params.username 分配给如下常量时

But whenever I try to assign params.username to a constant like below

const username:string =params.username;

它给了我以下错误

键入'字符串 |string[]' 不可分配给类型 'string'.类型 'string[]' 不能分配给类型 'string'.

Type 'string | string[]' is not assignable to type 'string'. Type 'string[]' is not assignable to type 'string'.

我的完整代码如下

import * as URL from 'url'; public getUserByName = async (req: Request, res: Response, next: NextFunction) => { var params = URL.parse(req.url, true).query; const username:string =params.username; try { const findOneUserData: Employee = await this.userService.findUserByName(username); res.status(200).json({ data: findOneUserData, message: 'findOne' }); } catch (error) { next(error); }

}

推荐答案

好的,所以我得到了我犯的错误.第一个是@ford04 在评论中提到的.我直接将 Object 分配给字符串.我在我的问题中改变了它.第二个是通过 toString() 函数将解析的查询字符串转换为字符串.

Okay ,so I got the mistake that I made. The first one was what @ford04 has mentioned in the comment. I was directly assigning Object to the string. I changed it in my question. The second was converted the parsed query-string to string by toString() function.

public getUserByName = async(req: Request, res: Response, next: NextFunction) => { var params = URL.parse(req.url, true).query; console.log(params.username); const username: string = params.username.toString(); //this is the key try { const findOneUserData: Employee = await this.userService.findUserByName(username); res.status(200).json({ data: findOneUserData, message: 'findOne' }); } catch (error) { next(error); } }

更多推荐

"键入'字符串

本文发布于:2023-11-14 02:31:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585988.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   amp   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!