打字稿 - 'string 类型的参数 | (string | null)[]' 不能分配给类型为 'string' 的参数

时间:2021-03-29 10:13:28

标签: javascript typescript

我从以下代码中收到打字稿错误:

if (this.$route?.query?.domainName) {
  this.setDomain(this.$route.query.domainName);
}

以上代码抛出如下错误:

<块引用>

Typescript - 'string 类型的参数 | (string | null)[]' 不是 可分配给“字符串”类型的参数

 if (this.$route?.query?.domainName) {
   this.setDomain(this.$route.query.domainName);
                  ^
 }

我的 setDomain 函数只接受字符串类型的参数,如下所示:

setDomain(domain: string) {
  this.domainName = domain;
}

我不明白参数怎么可能为空,因为我正在使用 if 语句中的对象属性之后的嵌套 ? 检查对象属性是否存在。为什么会抛出这个错误?

1 个答案:

答案 0 :(得分:2)

在您的代码中,domainName 仍然可以是字符串以外的其他内容 - 数组 ((string | null)[])。您的条件保护只是验证它不是一个假值,而不是一个字符串。

如果你检查它是一个字符串,它应该可以工作。请注意,此示例将允许使用空字符串,而您当前的代码则不允许。

declare const $route: null | { query: null | { domainName: null | string | (string | null)[] } }
declare const setDomain: (domain: string) => void;

if ($route?.query?.domainName) {
    // reproduces your error
    setDomain($route.query.domainName);
}

if (typeof $route?.query?.domainName == "string") {
    // no error
    setDomain($route.query.domainName);
}

See in the typescript playground