由于TypeScript是强类型的,简单地使用if(){}来检查null和undefined听起来并不正确。
TypeScript有专门的函数或语法吗?
由于TypeScript是强类型的,简单地使用if(){}来检查null和undefined听起来并不正确。
TypeScript有专门的函数或语法吗?
当前回答
你可能想试试
if(!!someValue)
! !
解释
第一个!将表达式转换为布尔值。
如果someValue为假则为真,如果someValue为真则为假。这可能会让人困惑。
通过添加另一个!,表达式现在如果someValue为真则为真,如果someValue为假则为假,这更容易管理。
讨论
现在,为什么我要用if (!!someValue)来麻烦自己,而像if (someValue)这样的东西会给我相同的结果?
因为! !someValue恰好是一个布尔表达式,而someValue可以是任何东西。这种表达式现在可以编写如下函数(上帝,我们需要这样的函数):
isSomeValueDefined(): boolean {
return !!someValue
}
而不是:
isSomeValueDefined(): boolean {
if(someValue) {
return true
}
return false
}
我希望这能有所帮助。
其他回答
if( value ) {
}
如果value不为true,则求值为true:
零 未定义的 南 空字符串" 0 假
Typescript包含javascript规则。
TypeScript有专门的函数或语法糖吗
TypeScript完全理解JavaScript版本== null。
通过这样的检查,TypeScript会正确地排除null和undefined。
More
https://basarat.gitbook.io/typescript/recap/null-undefined
我总是这样写:
var foo:string;
if(!foo){
foo="something";
}
这将会很好,我认为它是非常可读的。
最简单的方法是使用:
import {isNullOrUndefined} from 'util';
比:
如果isNullOrUndefined (foo (!)
您可以使用三元运算符和新的空合并运算符轻松做到这一点。
首先:使用三元来检查它是否为真。如果是,则返回false,因此If语句不会运行。
第二:因为现在知道值是假的,所以如果值为空,可以使用空合并运算符返回true。由于它将为任何其他值返回自身,如果它不为null,则将使if语句正确失败。
let x = true; console.log("starting tests") if (x?false:x ?? true){ console.log(x,"is nullish") } x = false if (x?false:x ?? true){ console.log(x,"is nullish") } x = 0; if (x?false:x ?? true){ console.log(x,"is nullish") } x=1; if (x?false:x ?? true){ console.log(x,"is nullish") } x=""; if (x?false:x ?? true){ console.log(x,"is nullish") } x="hello world"; if (x?false:x ?? true){ console.log(x,"is nullish") } x=null; if (x?false:x ?? true){ console.log(x,"is nullish") } x=undefined; if (x?false:x ?? true){ console.log(x,"is nullish") }