由于TypeScript是强类型的,简单地使用if(){}来检查null和undefined听起来并不正确。
TypeScript有专门的函数或语法吗?
由于TypeScript是强类型的,简单地使用if(){}来检查null和undefined听起来并不正确。
TypeScript有专门的函数或语法吗?
当前回答
如果你正在使用TypeScript,让编译器检查空值和未定义值(或可能存在的)是一个更好的方法,而不是在运行时检查它们。(如果您确实想在运行时检查,那么正如许多答案所表明的那样,只需使用value == null)。
使用编译选项strictNullChecks告诉编译器阻塞可能的空值或未定义值。如果你设置了这个选项,然后有一个你想要允许null和undefined的情况,你可以定义类型为type | null | undefined。
其他回答
TypeScript有专门的函数或语法糖吗
TypeScript完全理解JavaScript版本== null。
通过这样的检查,TypeScript会正确地排除null和undefined。
More
https://basarat.gitbook.io/typescript/recap/null-undefined
我们使用一个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;
}
如果你正在使用TypeScript,让编译器检查空值和未定义值(或可能存在的)是一个更好的方法,而不是在运行时检查它们。(如果您确实想在运行时检查,那么正如许多答案所表明的那样,只需使用value == null)。
使用编译选项strictNullChecks告诉编译器阻塞可能的空值或未定义值。如果你设置了这个选项,然后有一个你想要允许null和undefined的情况,你可以定义类型为type | null | undefined。
在TypeScript 3.7中,我们现在有可选的链接和Nullish Coalescing来同时检查null和undefined,例如:
let x = foo?.bar.baz();
这段代码将检查foo是否有定义,否则它将返回undefined
旧方法:
if(foo != null && foo != undefined) {
x = foo.bar.baz();
}
这样的:
let x = (foo === null || foo === undefined) ? undefined : foo.bar();
if (foo && foo.bar && foo.bar.baz) { // ... }
与可选的链接将:
let x = foo?.bar();
if (foo?.bar?.baz) { // ... }
另一个新特性是Nullish Coalescing,例如:
let x = foo ?? bar(); // return foo if it's not null or undefined otherwise calculate bar
老方法:
let x = (foo !== null && foo !== undefined) ?
foo :
bar();
奖金
试试这个,用!!运算符和变量。
let check;
if (!!check) {
console.log('check is not null or not undefined');
} else {
console.log('check is null or undefined');
}
它在Angular中非常有用。 检查任何变量的undefined和null。