繁体   English   中英

Typescript - 'string | 类型的参数 (string | null)[]' 不能分配给“string”类型的参数

[英]Typescript - Argument of type 'string | (string | null)[]' is not assignable to parameter of type 'string'

我从以下代码中收到 typescript 错误:

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

上面的代码抛出以下错误:

Typescript - 'string | 类型的参数 (string | null)[]' 不能分配给“string”类型的参数

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

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

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

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

在您的代码中, 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);
}

见 typescript 操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM