[英]What's the correct type for a variable in TypeScript that's initially undefined?
I have a variable we'll call a
in this example:我有一个变量,我们将在此示例中调用
a
:
let a;
I only want to assign it a value if it meets one of the requirements in the switch statement:如果它满足 switch 语句中的要求之一,我只想为其分配一个值:
switch(someOtherVar) {
case "a": {
a = "123";
break;
}
case "b": {
a = "456";
break;
}
}
I then want to check if it has a value like so:然后我想检查它是否有这样的值:
if (a) {
// ...do something
}
This means a
can be a string
or undefined
, and it starts undefined
.这意味着
a
可以是string
或undefined
,并且它以undefined
开头。 If I don't declare the type then it throws the following error:如果我不声明类型,则会引发以下错误:
Variable 'a' implicitly has an 'any' type, but a better type may be inferred from usage.ts(7043)
变量 'a' 隐含地具有 'any' 类型,但可以从 usage.ts(7043) 推断出更好的类型
I'm not sure what the correct way to declare the type would be in this instance:我不确定在这种情况下声明类型的正确方法是什么:
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?
The correct type is string | undefined
正确的类型是
string | undefined
string | undefined
. string | undefined
。 Under srictNullChecks
, the type string
does not contain the undefined
value or the null
value.在
srictNullChecks
下,类型string
不包含undefined
值或null
值。 These two values have their own types undefined
and null
.这两个值有自己的类型
undefined
和null
。 So to have a variable that is string
or undefined
using a union is appropriate.因此,使用联合使用
string
或undefined
的变量是合适的。
Note that control flow analysis does a pretty good job of inferring the type for your specific use case if the variable is not referenced in a closure请注意,如果变量未在闭包中引用,则控制流分析可以很好地推断特定用例的类型
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
Your first suggestion is correct because a
can't be any
.您的第一个建议是正确的,因为
a
不能是any
。
You second suggestion still has the type any
.你的第二个建议仍然是类型
any
。 You would need to it as follows but that's basically the same as your first suggestion.您将需要如下所示,但这与您的第一个建议基本相同。
let a: string | undefined = undefined;
Your third suggestion will cause problems because the engine does not expect the value to be undefined.您的第三个建议将导致问题,因为引擎不希望该值未定义。
If you know it's a string, you could declare it as empty string and later check the length of the string.如果您知道它是一个字符串,则可以将其声明为空字符串,然后检查字符串的长度。
let a: string = "";
if (a.length > 0) {
// do something...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.