我知道这可能是一个经典的javascript问题,但我经常发现自己使用:
if (!something) {
//...
}
在TypeScript中验证此something
不是undefined
或null
。
这非常容易出错!在number
上使用时,“0”将匹配,当在enum
上使用时,第一项也将匹配(默认情况下,第一项的值为“0”)!
有没有办法在TypeScript中处理这个问题?有没有办法配置TypeScript以禁止除boolean
(和any
)之外的任何内容的感叹号?这种配置是否有意义,或者我错过了一些微不足道的东西?
应该:
if (something === null || something === undefined) {
//...
}
是否可以使用来验证是否定义了某些内容?有没有办法在团队中强制执行此操作?
答案 0 :(得分:2)
您可以使用strict-boolean-expressions TSLint规则禁止此类事件。
您可以看到规则here的一些示例,但这是与您的问题特别相关的摘录。规则发现错误的位置标有~~~
,错误消息写在该标记旁边:
/*** PrefixUnary Expressions ***/
/*** Invalid ***/
!!numType;
~~~~~~~ [This type is not allowed in the operand for the '!' operator because it is a number. Only booleans are allowed.]
!strType;
~~~~~~~ [This type is not allowed in the operand for the '!' operator because it is a string. Only booleans are allowed.]
!objType;
~~~~~~~ [This type is not allowed in the operand for the '!' operator because it is always truthy. Only booleans are allowed.]
!enumType;
~~~~~~~~ [This type is not allowed in the operand for the '!' operator because it is an enum. Only booleans are allowed.]
!!classType;
~~~~~~~~~ [This type is not allowed in the operand for the '!' operator because it is always truthy. Only booleans are allowed.]
!bwrapType;
~~~~~~~~~ [This type is not allowed in the operand for the '!' operator because it is always truthy. Only booleans are allowed.]
!!undefined;
~~~~~~~~~~ [This type is not allowed in the operand for the '!' operator because it is always truthy. Only booleans are allowed.]
~~~~~~~~~ [This type is not allowed in the operand for the '!' operator because it is always falsy. Only booleans are allowed.]
/*** Valid ***/
!!boolFn();
!boolExpr;
!!boolType;
/*** If Statement ***/
/*** Invalid ***/
if (numType) { /* statements */ }
~~~~~~~ [This type is not allowed in the 'if' condition because it is a number. Only booleans are allowed.]
if (objType) { /* statements */ }
~~~~~~~ [This type is not allowed in the 'if' condition because it is always truthy. Only booleans are allowed.]
if (strType) { /* statements */ }
~~~~~~~ [This type is not allowed in the 'if' condition because it is a string. Only booleans are allowed.]
if (bwrapType) { /* statements */ }
~~~~~~~~~ [This type is not allowed in the 'if' condition because it is always truthy. Only booleans are allowed.]
if (strFn()) { /* statements */ }
~~~~~~~ [This type is not allowed in the 'if' condition because it is a string. Only booleans are allowed.]
if (MyEnum.A) { /* statements */ }
~~~~~~~~ [This type is not allowed in the 'if' condition because it is an enum. Only booleans are allowed.]
if (classType) { /* statements */ }
~~~~~~~~~ [This type is not allowed in the 'if' condition because it is always truthy. Only booleans are allowed.]
要简要回答您的另一方面的问题,下面的代码剪切是检查某些内容是否定义的好方法:
if (something == null) {
// will enter here if `something === null || something === undefined`
}
有关上述
的更多详情,请参阅here