【问题标题】:Typescript - Argument of type 'string | (string | null)[]' is not assignable to parameter of type 'string'Typescript - 'string | 类型的参数(string | null)[]' 不能分配给“string”类型的参数
【发布时间】:2021-03-29 10:13:28
【问题描述】:

我收到以下代码的打字错误:

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 语句中的对象属性之后使用嵌套的 ? 检查对象属性是否存在。为什么会抛出这个错误?

【问题讨论】:

  • 你的参数仍然是一个可以为空的字符串,但是你的方法只接受一个不可为空的字符串作为参数。在传递参数之前,您需要将参数转换为不可为空的字符串。

标签: javascript typescript


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-04-27
    • 2021-10-02
    • 2018-04-05
    • 2021-09-06
    • 2018-02-10
    • 2021-10-06
    • 2020-04-15
    • 2022-01-17
    • 2022-08-18
    相关资源
    最近更新 更多