我有这样的代码:
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'.发布于 2019-05-16 08:09:29
Update:只在变量中存储参数值(TypeScript不为函数调用实现基于控制流的类型分析):
const topic = searchParams.get("topic");
const Search: string = topic ? topic : "100";这是因为如果没有找到搜索参数,URLSearchParams.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";https://stackoverflow.com/questions/56163578
复制相似问题