[英]Typescript: what's the difference between checking if a variable is empty vs. checking if it has a value?
I'm adding validation to my code and, to improve readability, wrote the following:我正在向我的代码添加验证,并且为了提高可读性,写了以下内容:
if (!uid) {
return {result: 0, message: 'You are not authorized.'}
}
The alternative would be to check if the variable exists:另一种方法是检查变量是否存在:
if (uid) {
//do some code
}
However, if I have a lot of different variables to validate, I don't like having to nest them like so:但是,如果我有很多不同的变量要验证,我不喜欢像这样嵌套它们:
if (uid) {
if (otherVar) {
//do some code
} else {
//else code 1
}
} else {
//else code 2
}
Is there any difference to doing method 1 vs method 2?做方法1和方法2有什么区别吗?
The answer:答案:
true
, then it will return true
.true
,那么它将返回true
。true
.true
。 My opinion , you don't actually have to do it like that.我的意见,你实际上不必那样做。 Instead, you can use optional chaining operator in order to make safe checks inside an object.
相反,您可以使用可选的链接运算符来在 object 内部进行安全检查。 For example:
例如:
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name; // notice the usage of '?'
console.log(dogName); // will return 'undefined' as 'dog' object does not exist in that object.
Quoting MDN Docs:引用 MDN 文档:
The?.
这?。 operator functions similarly to the.
运算符的功能类似于。 chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined.
链接运算符,除了如果引用为空(null 或未定义)时不会导致错误,表达式会短路并返回未定义的值。 When used with function calls, it returns undefined if the given function does not exist.
当与 function 调用一起使用时,如果给定的 function 不存在,则返回 undefined。
From there, you can use optional chaining in order to simplify your nested blocks - like using a global error handler.从那里,您可以使用可选链接来简化嵌套块 - 就像使用全局错误处理程序一样。
const result = uid?.otherVar?; // imagine 'otherVar' does not exist!
if (!result) return handleResult();
Further reading:进一步阅读:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.