Dav*_*Liu 320 typescript
由于TypeScript是强类型的,因此仅使用if () {}检查null和undefined听起来不对.
TypeScript是否具有专用功能或语法糖?
Fen*_*ton 326
使用杂耍检查,你可以测试两个null和undefined一个命中:
if (x == null) {
Run Code Online (Sandbox Code Playgroud)
如果使用严格检查,则null对于未定义变量的值设置为和将不会为true的值将为true:
if (x === null) {
Run Code Online (Sandbox Code Playgroud)
您可以使用此示例尝试使用各种值:
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');
Run Code Online (Sandbox Code Playgroud)
产量
"a == null"
"a未定义"
"b == null"
"b === null"
Ram*_*ğır 229
if( value ) {
}
Run Code Online (Sandbox Code Playgroud)
将评估true如果value不是:
nullundefinedNaN''0falsetypescript包括javascript规则.
Fat*_*med 99
在TypeScript 3.7 中,我们现在有了Optional chaining 和Nullish Coalescing来同时检查null和undefined,例如:
let x = foo?.bar.baz();
Run Code Online (Sandbox Code Playgroud)
此代码将检查 foo 是否已定义,否则将返回 undefined
旧方式:
if(foo != null && foo != undefined) {
x = foo.bar.baz();
}
Run Code Online (Sandbox Code Playgroud)
这个:
let x = (foo === null || foo === undefined) ? undefined : foo.bar();
if (foo && foo.bar && foo.bar.baz) { // ... }
Run Code Online (Sandbox Code Playgroud)
使用可选链接将是:
let x = foo?.bar();
if (foo?.bar?.baz) { // ... }
Run Code Online (Sandbox Code Playgroud)
另一个新功能是Nullish Coalescing,例如:
let x = foo ?? bar(); // return foo if it's not null or undefined otherwise calculate bar
Run Code Online (Sandbox Code Playgroud)
旧方法:
let x = (foo !== null && foo !== undefined) ?
foo :
bar();
Run Code Online (Sandbox Code Playgroud)
dan*_*ilo 43
虽然 Typescript 是一种强类型语言,但它在继承自 Javascript 的指针和变量初始化方面也存在同样的问题。
JavaScript 不会检查变量是否存在于上下文中,这是常见的undefined状态。
评估值是否不是 null、undefined、0、false、""、 或NaN:
if ( value )
or
if ( !!value )
Run Code Online (Sandbox Code Playgroud)
对于否定条件,检查值是否为null, undefined, 0, false, "",or NaN:
if ( !value )
Run Code Online (Sandbox Code Playgroud)
测试是否是null或undefined:
if ( value == null )
Run Code Online (Sandbox Code Playgroud)
仅测试null:
if ( value === null )
Run Code Online (Sandbox Code Playgroud)
仅测试undefined:
if ( value === undefined )
Run Code Online (Sandbox Code Playgroud)
1-如果值不是:,,,如果值为,,,,,,,,,,,,,,,,,,,
nullundefinedNaNempty string ''0falsenullundefinedNaNempty string0false
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');
}
Run Code Online (Sandbox Code Playgroud)
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');
}
Run Code Online (Sandbox Code Playgroud)
3-它将评估值是否为null或undefined
if ( value == null ) {
console.log('is null or undefined');
} else {
console.log('it isnt null neither undefined');
}
Run Code Online (Sandbox Code Playgroud)
4-使用布尔值测试不起作用。如果值为, , , ,则
它不会评估为true也不会评估为false ,
这两个条件将始终转到else条件。
但 value 是布尔变量除外。nullundefined0empty stringNaN
if ( value==true ) {
} else {
}
if ( value==false ) {
} else {
}
Run Code Online (Sandbox Code Playgroud)
bas*_*rat 36
TypeScript是否具有专用函数或语法糖
不,我something == null和JavaScript一样.
Jua*_*dán 35
我在打字稿操场上做了不同的测试:
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);
Run Code Online (Sandbox Code Playgroud)
得到:
a is null or undefined
b is null or undefined
c is defined
Run Code Online (Sandbox Code Playgroud)
所以:
Ahm*_*mal 29
因为我正在使用基于打字稿的角度和角度,我将列出检查类型,null,空和未定义的可能方案.
这就是我所知道的
messagenullundefined此外,还有一个官方文档,您可以使用它来获取更多详细信息.
TL; DR
在JavaScript message实际上不是typeof(message) !== 'undefined' && message !== null它的一个undefined,message != null是message,但是null是undefined.
您可能还需要知道,message在JavaScript中值不是类型进行比较,但typeof(message) !== 'undefined' && message !== null比较的类型和的值,例如undefined但是message != null这同样为message和null例如undefined但message
更新:15-01-2019
经过一段时间深入到Typescript之后,我发现检查null和undefined的最佳和最稳定的方法如下.
// bad-file.ts
console.log(message)
Run Code Online (Sandbox Code Playgroud)
希望这有助于某人.
avi*_*rat 18
你可能想试试
if(!!someValue)
Run Code Online (Sandbox Code Playgroud)
与!!.
说明
第一个!将表达式转换为boolean值.
然后!someValue是true如果someValue是假的,false如果someValue是真的.这可能会令人困惑.
通过添加另一个!,表达式现在true如果someValue是真的,false如果someValue是假的,这更容易管理.
讨论
现在,为什么我懒得自己有if (!!someValue)当像if (someValue)本来给我同样的结果呢?
因为它!!someValue只是一个布尔表达式,而someValue绝对可能是任何东西.这种表达现在将会写下函数(而上帝我们需要那些),如:
isSomeValueDefined(): boolean {
return !!someValue
}
Run Code Online (Sandbox Code Playgroud)
代替:
isSomeValueDefined(): boolean {
if(someValue) {
return true
}
return false
}
Run Code Online (Sandbox Code Playgroud)
我希望它有所帮助.
Ser*_*lov 12
因为Typescript 2.x.x您应该按照以下方式进行操作(使用类型guard):
tl; dr
function isDefined<T>(value: T | undefined | null): value is T {
return <T>value !== undefined && <T>value !== null;
}
Run Code Online (Sandbox Code Playgroud)
为什么?
这样,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
}
}
Run Code Online (Sandbox Code Playgroud)
示例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
}
}
Run Code Online (Sandbox Code Playgroud)
更新(2020 年 9 月 4 日)
您现在可以使用??运算符来验证null和undefined“值”并设置默认值。例如:
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
Run Code Online (Sandbox Code Playgroud)
作为一个详细的方法,如果你想比较空和不确定值ONLY,使用下面的示例代码,以供参考:
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}`);
}
Run Code Online (Sandbox Code Playgroud)
如果incomingValue未声明,TypeScript 应返回异常。如果已声明但未定义,console.log()则将返回“传入值:未定义”。请注意,我们没有使用严格的等于运算符。
“正确”方式(查看其他答案以获取详细信息),如果incomingValue不是boolean类型,则仅评估其值是否为真,这将根据常量/变量类型进行评估。一个true字符串必须使用被明确定义为字符串= ''分配。如果不是,它将被评估为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"
}
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您使用的是TypeScript,那么让编译器检查空值和未定义(或其可能性)是一种更好的方法,而不是在运行时检查它们.(如果你想在运行时检查,那么尽可能多的答案表明,只需使用value == null).
使用compile选项strictNullChecks告诉编译器阻塞可能的null或未定义的值.如果设置了此选项,然后有一个情况下,你都希望允许null和undefined,您可以定义类型Type | null | undefined.
如果你想通过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
Run Code Online (Sandbox Code Playgroud)
不完全是语法糖,但是在您的tslint规则严格时很有用。
| 归档时间: |
|
| 查看次数: |
367865 次 |
| 最近记录: |