![](/img/trans.png)
[英]Argument of type 'string | undefined' is not assignable to parameter of type 'string' - TypeScript error
[英]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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.