首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >打字问题URLSearchParams

打字问题URLSearchParams
EN

Stack Overflow用户
提问于 2019-05-16 07:55:11
回答 1查看 2.8K关注 0票数 0

我有这样的代码:

代码语言:javascript
复制
const paramsString = "q=URLUtils.searchParams&topic=api";
const searchParams = new URLSearchParams(paramsString);
const Search: string = searchParams.get("topic")?
searchParams.get("topic"):"100";

我知道这个错误:

代码语言:javascript
复制
Type 'string | null' is not assignable to type 'string'.
  Type 'null' is not assignable to type 'string'.
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-16 08:09:29

Update:只在变量中存储参数值(TypeScript不为函数调用实现基于控制流的类型分析):

代码语言:javascript
复制
const topic = searchParams.get("topic");
const Search: string = topic ? topic : "100";

这是因为如果没有找到搜索参数,URLSearch​Params​.get()会返回null,所以searchParams.get("Search")可以是null

启用了strictNullChecks编译器选项,因此出现了错误。

要解决这个问题,可以将变量键入为string | null

代码语言:javascript
复制
const Search: string | null = searchParams.get("topic") 
  ? searchParams.get("Search")
  : "100";

或者,如果,您确信查询字符串有一个“搜索”参数,您可以使用非空断言运算符

代码语言:javascript
复制
const Search: string = searchParams.get("topic")
  ? searchParams.get("Search")!
  : "100";
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56163578

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档