注意: 如果您是 TypeScript 新手,请先查看我们的 TypeScript 入门 教程。
TypeScript undefined
在 TypeScript 中,如果一个变量在声明时没有赋值,它的类型会被隐式地推断为 undefined
。例如:
let userName: string;
console.log(userName); // undefined
console.log(typeof userName);
userName = "Felix";
console.log(typeof userName);
正如你所见,我们声明了一个字符串变量 userName
,但没有对其进行初始化。因此,TypeScript 将其值和类型都赋为了 undefined
。
但是,一旦我们将值 "Felix"
赋给它,该变量的类型就变成了 string
。
显式赋值 undefined
你也可以显式地赋值 undefined
let userName: string | undefined = "Felix";
userName = undefined;
console.log(userName); // undefined
注意:为了允许 undefined
,在指定变量类型时明确包含它(例如:string | undefined
)是一个好习惯。否则,某些编译器可能会在编译时发出警告。
TypeScript null
TypeScript 中的 null
表示有意地缺少任何对象值
let num: number | null = null;
console.log(typeof num); // object
console.log(num); // null
在这里,我们将 null
赋给了 num
变量。但请注意,typeof num
输出的是 object
。
稍后在本教程中我们将解释原因。
注意:TypeScript 区分 null
和 undefined
,并且在使用 --strictNullChecks 时,你必须在类型中显式包含 null
或 undefined
。
假值
null
和 undefined
在 TypeScript 中都属于假值(就像 JavaScript 一样)
if (null || undefined) {
console.log("true");
}
else {
console.log("false");
}
输出
error: This kind of expression is always falsy.
在这里,TypeScript 会给出编译时错误,因为 if (null || undefined)
总是假值。
因此,使用 if...else 语句检查一个总是假值的表达式是一个逻辑错误,TypeScript 不允许这样做。
null 和 undefined 与 Boolean()
null
和 undefined
使用 Boolean()
转换时也会评估为 false
console.log(Boolean(undefined)); // false
console.log(Boolean(null)); // false
TypeScript typeof: null 和 undefined
const a = null;
console.log(typeof a); // "object"
let b: undefined;
console.log(typeof b); // "undefined"
与 JavaScript 行为相同:typeof null === "object"
。
这是 JavaScript 中一个长期存在的 bug,由于担心破坏旧的 JavaScript 代码而未被修复。
实际上,null
不是一个对象,而是原始值。
TypeScript 默认值:null vs undefined
当将 undefined
传递给带有默认值的函数参数时,会使用默认值
function test(x: number = 10) {
console.log(x);
}
test(undefined); // 10
但是,当你将 null
传递给带有默认参数的函数时,函数会将其 null
作为值。例如:
function test(x: number = 10) {
console.log(x);
}
test(null); // null
比较 null 和 undefined
使用相等运算符 ==
console.log(null == undefined); // true
使用严格相等运算符 ===
console.log(null === undefined); // false
另请阅读