由于TypeScript是强类型的,只需使用if () {}
来检查null和undefined听起来不对。
TypeScript是否具有专用功能或语法糖?
使用杂耍检查,你可以在一击中测试null
和undefined
:
if (x == null) {
如果使用严格检查,则只有设置为null
的值才会成立,并且对于未定义的变量不会评估为true:
if (x === null) {
您可以使用此示例尝试使用各种值:
var a: number;
var b: number = null;
function check(x, name) {
if (x == null) {
console.log(name + ' == null');
}
if (x === null) {
console.log(name + ' === null');
}
if (typeof x === 'undefined') {
console.log(name + ' is undefined');
}
}
check(a, 'a');
check(b, 'b');
产量
“a == null”
“a未定义”
“b == null”
“b === null”
如果你想在没有将tslint
设置为strict-boolean-expressions
或allow-null-union
的情况下传递allow-undefined-union
,你需要使用来自isNullOrUndefined
的node
模块的util
或者自己动手:
// tslint:disable:no-null-keyword
export const isNullOrUndefined =
<T>(obj: T | null | undefined): obj is null | undefined => {
return typeof obj === "undefined" || obj === null;
};
// tslint:enable:no-null-keyword
不完全是语法糖,但在你的tslint规则严格时很有用。
所有,
如果你正在使用一个对象,那么获得最多选票的答案就不会真正起作用。在这种情况下,如果没有财产,检查将无效。这就是我们案例中的问题:请参阅此示例:
var x =
{ name: "Homer", LastName: "Simpson" };
var y =
{ name: "Marge"} ;
var z =
{ name: "Bart" , LastName: undefined} ;
var a =
{ name: "Lisa" , LastName: ""} ;
var hasLastNameX = x.LastName != null;
var hasLastNameY = y.LastName != null;
var hasLastNameZ = z.LastName != null;
var hasLastNameA = a.LastName != null;
alert (hasLastNameX + ' ' + hasLastNameY + ' ' + hasLastNameZ + ' ' + hasLastNameA);
var hasLastNameXX = x.LastName !== null;
var hasLastNameYY = y.LastName !== null;
var hasLastNameZZ = z.LastName !== null;
var hasLastNameAA = a.LastName !== null;
alert (hasLastNameXX + ' ' + hasLastNameYY + ' ' + hasLastNameZZ + ' ' + hasLastNameAA);
结果:
true , false, false , true (in case of !=)
true , true, true, true (in case of !==) => so in this sample not the correct answer
plunker链接:qazxsw poi
https://plnkr.co/edit/BJpVHD95FhKlpHp1skUE检查的更快更短的表示法可以是:
null
这一行相当于:
value == null ? "UNDEFINED" : value
特别是当你有很多if(value == null) {
console.log("UNDEFINED")
} else {
console.log(value)
}
检查它是一个很好的简短符号。
我有这个问题,一些答案对null
很好,但JS
不是这里的原因。
TS
这一切都很好,因为JS没有类型
//JS
let couldBeNullOrUndefined;
if(couldBeNullOrUndefined == null) {
console.log('null OR undefined', couldBeNullOrUndefined);
} else {
console.log('Has some value', couldBeNullOrUndefined);
}
在TS中如果变量没有用//TS
let couldBeNullOrUndefined?: string | null; // THIS NEEDS TO BE TYPED AS undefined || null || Type(string)
if(couldBeNullOrUndefined === null) { // TS should always use strict-check
console.log('null OR undefined', couldBeNullOrUndefined);
} else {
console.log('Has some value', couldBeNullOrUndefined);
}
定义,当你试图检查null
时null
|编译器会抱怨。
tslint
//tslint.json
...
"triple-equals":[true],
...
迟到加入这个线程,但我发现这个JavaScript hack在检查值是否未定义时非常方便
let couldBeNullOrUndefined?: string; // to fix it add | null
Types of property 'couldBeNullOrUndefined' are incompatible.
Type 'string | null' is not assignable to type 'string | undefined'.
Type 'null' is not assignable to type 'string | undefined'.
您可以使用
import * as isNil from 'ramda/src/isNil';
totalAmount = isNil(totalAmount ) ? 0 : totalAmount ;
由于TypeScript是ES6 JavaScript的类型超集。而lodash是一个javascript库。
使用lodash检查value是null还是undefined可以使用if(x === undefined)
完成。
_.isNil()
value(*):要检查的值。
(boolean):如果value为null,则返回true,否则返回false。
_.isNil(value)
_.isNil(null);
// => true
_.isNil(void 0);
// => true
_.isNil(NaN);
// => false
if( value ) {
}
如果true
不是,将评估value
:
null
undefined
NaN
''
0
false
typescript包括javascript规则。
我在打字稿操场上做了不同的测试:
http://www.typescriptlang.org/play/
let a;
let b = null;
let c = "";
var output = "";
if (a == null) output += "a is null or undefined\n";
if (b == null) output += "b is null or undefined\n";
if (c == null) output += "c is null or undefined\n";
if (a != null) output += "a is defined\n";
if (b != null) output += "b is defined\n";
if (c != null) output += "c is defined\n";
if (a) output += "a is defined (2nd method)\n";
if (b) output += "b is defined (2nd method)\n";
if (c) output += "c is defined (2nd method)\n";
console.log(output);
得到:
a is null or undefined
b is null or undefined
c is defined
所以:
TypeScript是否具有专用函数或语法糖
不,我只是像JavaScript一样做something == null
。
我认为这个答案需要更新,检查旧答案的编辑历史。
基本上,您有三个不同的情况null,undefined和unclared,请参阅下面的代码段。
// bad-file.ts
console.log(message)
你会得到一个错误,说变量message
是未定义的(也就是未声明的),当然,Typescript编译器不应该让你这样做,但真的没有什么可以阻止你。
// evil-file.ts
// @ts-gnore
console.log(message)
编译器很乐意只编译上面的代码。因此,如果您确定所有变量都已声明,则可以执行此操作
if ( message != null ) {
// do something with the message
}
上面的代码将检查null
和undefined
,但如果message
变量可能未声明(为安全起见),您可以考虑以下代码
if ( typeof(message) !== 'undefined' && message !== null ) {
// message variable is more than safe to be used.
}
注意:这里的顺序typeof(message) !== 'undefined' && message !== null
是非常重要的,你必须首先检查undefined
状态,它将与message != null
一样,谢谢@Jaider。
if(data){}
这是意思!数据
你可能想试试
if(!!someValue)
与!!
。
说明
第一个!
将你的表达变成boolean
值。
然后!someValue
是true
如果someValue
是falsy和false
如果someValue
是truthy。这可能会令人困惑。
通过添加另一个!
,表达式现在是true
,如果someValue
是真正的false
,如果someValue
是假的,这更容易管理。
讨论
现在,为什么当if (!!someValue)
之类的东西给我同样的结果时,我会为if (someValue)
打扰自己?
因为!!someValue
恰好是一个布尔表达式,而someValue
可能绝对是任何东西。这种表达现在将会写下函数(而上帝我们需要那些),如:
isSomeValueDefined(): boolean {
return !!someValue
}
代替:
isSomeValueDefined(): boolean {
if(someValue) {
return true
}
return false
}
我希望它有所帮助。
对于Typescript 2.x.x
,您应该采用以下方式:
tl;博士
function isDefined<T>(value: T | undefined | null): value is T {
return <T>value !== undefined && <T>value !== null;
}
为什么?
这样,isDefined()
将尊重变量的类型,以下代码将知道这个检查帐户。
示例1 - 基本检查:
function getFoo(foo: string): void {
//
}
function getBar(bar: string| undefined) {
getFoo(bar); //ERROR: "bar" can be undefined
if (isDefined(bar)) {
getFoo(bar); // Ok now, typescript knows that "bar' is defined
}
}
示例2 - 类型方面:
function getFoo(foo: string): void {
//
}
function getBar(bar: number | undefined) {
getFoo(bar); // ERROR: "number | undefined" is not assignable to "string"
if (isDefined(bar)) {
getFoo(bar); // ERROR: "number" is not assignable to "string", but it's ok - we know it's number
}
}
如果您使用的是TypeScript,那么让编译器检查空值和未定义(或其可能性)是一种更好的方法,而不是在运行时检查它们。 (如果你想在运行时检查,那么尽可能多的答案表明,只需使用value == null
)。
使用编译选项strictNullChecks
告诉编译器阻塞可能的null或未定义的值。如果设置此选项,然后有一种情况需要允许null和undefined,则可以将类型定义为Type | null | undefined
。