Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在Typescript上设置location.href而不出错?_Javascript_Reactjs_Typescript_Ecmascript 6 - Fatal编程技术网

Javascript 如何在Typescript上设置location.href而不出错?

Javascript 如何在Typescript上设置location.href而不出错?,javascript,reactjs,typescript,ecmascript-6,Javascript,Reactjs,Typescript,Ecmascript 6,我有以下代码: const assetsRedirection=(props:AssetsProps):null=>{ constquery=queryString.parse(props.location.search); const url=query.url; 如果(url){ window.location.href=url; } 返回null; }; 我收到这个错误: Type 'string | string[]' is not assignable to type 'string

我有以下代码:

const assetsRedirection=(props:AssetsProps):null=>{
constquery=queryString.parse(props.location.search);
const url=query.url;
如果(url){
window.location.href=url;
}
返回null;
};
我收到这个错误:

Type 'string | string[]' is not assignable to type 'string'.
  Type 'string[]' is not assignable to type 'string'.ts(2322)
它来自这一行
window.location.href=url
恰好位于
window.location.href


我怎样才能摆脱它?

您应该检查url是数组还是字符串。如果是arry,则应选择正确的arry

if (url instanceof Array) 
  url = url[0]

您还必须将url的删除从
const url=query.url
更改为
let url=query.url

您应该检查url是数组还是字符串。如果是arry,则应选择正确的arry

if (url instanceof Array) 
  url = url[0]

您还必须将url的取消限制从
const url=query.url
更改为
let url=query.url

这是因为在查询字符串规范中允许查询字符串参数为数组。您可以检查
queryString.parse
方法的类型,以查看它返回的确切内容。我猜它考虑了规范,还考虑了数组

假设您控制查询字符串并确保
url
始终是一个字符串,则可以强制转换它:

const url = <string>query.url;

之所以会发生这种情况,是因为查询字符串规范中允许查询字符串参数为数组。您可以检查
queryString.parse
方法的类型,以查看它返回的确切内容。我猜它考虑了规范,还考虑了数组

假设您控制查询字符串并确保
url
始终是一个字符串,则可以强制转换它:

const url = <string>query.url;

?嗨,@jornsharpe你能详细说明一下吗?我已经添加了一个到文档的链接。@jornsharpe它起作用了。我做了
window.location.href=url作为字符串。如果你给出一个答案,我可以给你一张绿色的支票。?嗨,@jornsharpe你能详细说明一下吗?我已经添加了一个到文档的链接。@jornsharpe它起作用了。我做了
window.location.href=url作为字符串。如果你给出一个答案,我可以给你一个很酷的绿色复选框
I get
属性“string”在类型“JSX.intrinsiceelements”上不存在。ts(2339)
JSX元素“string”没有相应的结束标记。ts(17008)
Ah,react正在将其解释为JSX。您需要改为使用
as
进行强制转换:如果我执行
const url=query.url
I get
属性“string”在类型“JSX.intrinsiceelements”上不存在。ts(2339)
JSX元素“string”没有相应的结束标记。ts(17008)
Ah,react正在将其解释为JSX。您需要改为使用
as
进行强制转换: