由于TypeScript是强类型的,简单地使用if(){}来检查null和undefined听起来并不正确。
TypeScript有专门的函数或语法吗?
由于TypeScript是强类型的,简单地使用if(){}来检查null和undefined听起来并不正确。
TypeScript有专门的函数或语法吗?
当前回答
我在typescript操场上做了不同的测试:
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
so:
检查(a == null)是否正确,以知道a是否为空或未定义 检查(a != null)是否正确,以知道是否定义了a 检查(a)是否错误,以知道a是否被定义
其他回答
我们使用一个helper hasValue来检查null /undefined,并通过TypeScript确保不执行不必要的检查。(后者类似于TS如何抱怨if ("a" === undefined),因为它总是假的)。
始终使用这个始终是安全的,不像!val匹配空字符串,零等。它还避免了模糊==匹配的使用,这几乎总是一个坏的做法-没有必要引入异常。
type NullPart<T> = T & (null | undefined);
// Ensures unnecessary checks aren't performed - only a valid call if
// value could be nullable *and* could be non-nullable
type MustBeAmbiguouslyNullable<T> = NullPart<T> extends never
? never
: NonNullable<T> extends never
? never
: T;
export function hasValue<T>(
value: MustBeAmbiguouslyNullable<T>,
): value is NonNullable<MustBeAmbiguouslyNullable<T>> {
return (value as unknown) !== undefined && (value as unknown) !== null;
}
export function hasValueFn<T, A>(
value: MustBeAmbiguouslyNullable<T>,
thenFn: (value: NonNullable<T>) => A,
): A | undefined {
// Undefined matches .? syntax result
return hasValue(value) ? thenFn(value) : undefined;
}
我有这个问题,一些答案工作只是很好的JS,但不是TS这里的原因。
//JS
let couldBeNullOrUndefined;
if(couldBeNullOrUndefined == null) {
console.log('null OR undefined', couldBeNullOrUndefined);
} else {
console.log('Has some value', couldBeNullOrUndefined);
}
这很好,因为JS没有类型
//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);
}
在TS中,如果变量未定义为null,当您试图检查该null时,tslint |编译器将报错。
//tslint.json
...
"triple-equals":[true],
...
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'.
简单的答案
虽然Typescript是一种强类型语言,但它在继承自Javascript的指针和变量初始化方面也存在同样的问题。 Javascript不检查变量在上下文中是否存在,这是很常见的未定义状态。
如果值为null,undefined,0,false,"",NaN:
if ( value )
or
if ( !!value )
对于否定条件句:
if ( !value )
测试是否为空或未定义:
if ( value == null )
只测试null:
if ( value === null )
只测试undefined:
if ( value === undefined )
更详细的回答
1-如果value不是:null, undefined, NaN,空字符串",0,false,它将计算为true 如果值为null、undefined、NaN、空字符串、0或false,将转到else条件。
if ( value ) {
console.log('value is something different from 0, "", false, NaN, null, undefined');
} else {
console.log('value is 0, "", false, NaN, null or undefined');
}
if ( !!value ) {
console.log('value is something different from 0, "", false, NaN, null, undefined');
} else {
console.log('value is 0, "", false, NaN, null or undefined');
}
2-如果你想要一个否定的条件,那么你需要使用:
if ( !value ) {
console.log('value is 0, "", false, NaN, null or undefined');
} else {
console.log('value is something different from 0, "", false, NaN, null, undefined');
}
3-如果value为空或未定义,它将计算
if ( value == null ) {
console.log('is null or undefined');
} else {
console.log('it isnt null neither undefined');
}
4-使用布尔条件不工作。 如果值为null, undefined, 0,空字符串,NaN,它将不会计算为true或false 这两个条件都会转到else条件。 如果value是布尔变量,则例外。
if ( value==true ) {
} else {
}
if ( value==false ) {
} else {
}
我总是这样写:
var foo:string;
if(!foo){
foo="something";
}
这将会很好,我认为它是非常可读的。
All,
得票最多的答案,如果你在研究一个对象,就不适用了。在这种情况下,如果属性不存在,检查将不起作用。这就是我们案例中的问题:请看这个例子:
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
plunkr链接:https://plnkr.co/edit/BJpVHD95FhKlpHp1skUE