【问题标题】:How can I set location.href on Typescript without getting errors?如何在 Typescript 上设置 location.href 而不会出错?
【发布时间】:2020-06-08 17:51:01
【问题描述】:

我有这个代码:

  const assetsRedirection = (props: AssetsProps): null => {
    const query = queryString.parse(props.location.search);
    const url = query.url;    

    if (url) {
      window.location.href = url;
    }

    return 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

我怎样才能摆脱它?

【问题讨论】:

  • 嗨,@jonrsharpe 你能详细说明一下吗?
  • 我添加了文档链接。
  • @jonrsharpe 成功了。我做了window.location.href = url as string;。如果你回答我可以给你一个很酷的绿色检查。

标签: javascript reactjs typescript ecmascript-6


【解决方案1】:

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

假设您控制查询字符串并确定 url 将始终是一个字符串,您可以直接转换它:

const url = <string>query.url;

更新:由于这是 jsx,它将括号解释为 html,因此您需要使用 as 进行转换:

const url = query.url as string;

【讨论】:

  • 如果我这样做 const url = &lt;string&gt;query.url; 我会得到 Property 'string' does not exist on type 'JSX.IntrinsicElements'.ts(2339)JSX element 'string' has no corresponding closing tag.ts(17008)
  • 啊,react 将其解释为 jsx。您需要使用 as 进行投射:stackoverflow.com/questions/37613981/…
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 2011-01-23
    • 2019-04-27
    • 2018-12-20
    相关资源
    最近更新 更多