由于TypeScript是强类型的,简单地使用if(){}来检查null和undefined听起来并不正确。
TypeScript有专门的函数或语法吗?
由于TypeScript是强类型的,简单地使用if(){}来检查null和undefined听起来并不正确。
TypeScript有专门的函数或语法吗?
当前回答
对于Typescript 2.x。X你应该用以下方式(使用类型保护):
博士tl;
function isDefined<T>(value: T | undefined | null): value is T {
return <T>value !== undefined && <T>value !== null;
}
Why?
这样,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 2.x。X你应该用以下方式(使用类型保护):
博士tl;
function isDefined<T>(value: T | undefined | null): value is T {
return <T>value !== undefined && <T>value !== null;
}
Why?
这样,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
}
}
更新(2020年9月4日)
你现在可以使用??运算符来验证空值和未定义的“值”并设置默认值。例如:
const foo = null;
const bar = foo ?? 'exampleValue';
console.log(bar); // This will print 'exampleValue' due to the value condition of the foo constant, in this case, a null value
作为一种详细的方式,如果你想比较空值和未定义值,使用下面的示例代码作为参考:
const incomingValue : string = undefined;
const somethingToCompare : string = incomingValue; // If the line above is not declared, TypeScript will return an excepion
if (somethingToCompare == (undefined || null)) {
console.log(`Incoming value is: ${somethingToCompare}`);
}
如果incomingValue没有声明,TypeScript应该返回一个异常。如果声明了但没有定义,console.log()将返回“Incoming value is: undefined”。注意,我们没有使用严格的等于运算符。
“正确”的方法(检查其他答案的细节),如果incomingValue不是一个布尔类型,只是评估它的值是否为真,这将根据常量/变量类型进行评估。真正的字符串必须使用= "赋值显式地定义为字符串。否则,它将被赋值为false。让我们使用相同的上下文来检查这个情况:
const incomingValue : string = undefined;
const somethingToCompare0 : string = 'Trumpet';
const somethingToCompare1 : string = incomingValue;
if (somethingToCompare0) {
console.log(`somethingToCompare0 is: ${somethingToCompare0}`); // Will return "somethingToCompare0 is: Trumpet"
}
// Now, we will evaluate the second constant
if (somethingToCompare1) {
console.log(`somethingToCompare1 is: ${somethingToCompare1}`); // Launched if incomingValue is defined
} else {
console.log(`somethingToCompare1 is: ${somethingToCompare1}`); // Launched if incomingValue is undefined. Will return "somethingToCompare1 is: undefined"
}
如果你正在使用TypeScript,让编译器检查空值和未定义值(或可能存在的)是一个更好的方法,而不是在运行时检查它们。(如果您确实想在运行时检查,那么正如许多答案所表明的那样,只需使用value == null)。
使用编译选项strictNullChecks告诉编译器阻塞可能的空值或未定义值。如果你设置了这个选项,然后有一个你想要允许null和undefined的情况,你可以定义类型为type | null | undefined。
通常我做杂耍检查,芬顿已经说过了。 为了让它更具可读性,你可以使用ramda中的isNil。
import * as isNil from 'ramda/src/isNil';
totalAmount = isNil(totalAmount ) ? 0 : totalAmount ;
简单的答案
虽然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 {
}