如何检查TypeScript中的null和undefined ?
参考答案:
通过使用一个缓冲检查,我们可以检查空和未定义:
if (x == null) {
}如果我们使用严格的检查,它将总是对设置为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 is undefined"
"b == null"
"b === null"题目要点:
作答思路:
在TypeScript中,可以通过类型保护(Type Guard)来检查null和undefined。以下是几种检查null和undefined的方法:
使用typeof和===操作符:
typescriptif (typeof value === 'undefined' || value === null) { // 处理null或undefined }使用
!操作符进行强制类型转换:typescriptif (value !== null && value !== undefined) { // 确保value不是null或undefined }使用联合类型:
typescriptfunction check(value: string | null | undefined): boolean { return value !== null && value !== undefined; }使用类型断言:
typescriptif (value as string !== undefined) { // 假设value是string类型,并且不为undefined }
考察要点:
- 类型保护:理解如何使用类型保护来检查
null和undefined。 - 强制类型转换:了解如何使用
!操作符进行强制类型转换。