[英]What's the usefulness in declaring a variable type as the property of an interface (in typescript)
[英]What's the correct type for a variable in TypeScript that's initially undefined?
我有一個變量,我們將在此示例中調用a
:
let a;
如果它滿足 switch 語句中的要求之一,我只想為其分配一個值:
switch(someOtherVar) {
case "a": {
a = "123";
break;
}
case "b": {
a = "456";
break;
}
}
然后我想檢查它是否有這樣的值:
if (a) {
// ...do something
}
這意味着a
可以是string
或undefined
,並且它以undefined
開頭。 如果我不聲明類型,則會引發以下錯誤:
變量 'a' 隱含地具有 'any' 類型,但可以從 usage.ts(7043) 推斷出更好的類型
我不確定在這種情況下聲明類型的正確方法是什么:
1. let a: string | undefined; // this seems to be the best way
2. let a = undefined; // this declares it as any which I don't want
3: let a: string; // is this correct if it can be undefined?
正確的類型是string | undefined
string | undefined
。 在srictNullChecks
下,類型string
不包含undefined
值或null
值。 這兩個值有自己的類型undefined
和null
。 因此,使用聯合使用string
或undefined
的變量是合適的。
請注意,如果變量未在閉包中引用,則控制流分析可以很好地推斷特定用例的類型
let a = undefined; // any here
switch(someOtherVar) {
case "a": {
a = "123";
break;
}
case "b": {
a = "456";
break;
}
}
// function x() { console.log(a)}; // if referenced in another function you get an error
a; // but the type of a is string | undefined
您的第一個建議是正確的,因為a
不能是any
。
你的第二個建議仍然是類型any
。 您將需要如下所示,但這與您的第一個建議基本相同。
let a: string | undefined = undefined;
您的第三個建議將導致問題,因為引擎不希望該值未定義。
如果您知道它是一個字符串,則可以將其聲明為空字符串,然后檢查字符串的長度。
let a: string = "";
if (a.length > 0) {
// do something...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.