首页 > 解决方案 > 输入问题 URLSearchParams

问题描述

我有这个代码:

const paramsString = "q=URLUtils.searchParams&topic=api";
const searchParams = new URLSearchParams(paramsString);
const Search: string = searchParams.get("topic")?
searchParams.get("topic"):"100";

我收到此错误:

Type 'string | null' is not assignable to type 'string'.
  Type 'null' is not assignable to type 'string'.

标签: reactjstypescript

解决方案


更新:只需将参数值存储在变量中(TypeScript 没有为函数调用实现基于控制流的类型分析):

const topic = searchParams.get("topic");
const Search: string = topic ? topic : "100";

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

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

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

const Search: string | null = searchParams.get("topic") 
  ? searchParams.get("Search")
  : "100";

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

const Search: string = searchParams.get("topic")
  ? searchParams.get("Search")!
  : "100";

推荐阅读