Appearance
null 与 undefined
在 JavaScript 中,null与undefined都表示缺少什么,Typescript 也支持这两个值,并且都有各自的类型,类型名称就是 null 与 undefined。
这两个类型比较特殊,在 TS 中,undefined类型只有undefined一个值,null类型也只有null一个值。
我们在写 JavaScript 的时候,这两个在语义上有细微的差别,undefined一般表示尚未定义,而null表示缺少值。
null与undefined在没有开启strictNullChecks检查的情况下(tsconfig.json 中设置了strict:true默认开始,如果想关闭,可以设置strictNullChecks:false),会被视为其他类型的子类型,比如 string 类型会被认为包含了null与undefined
null与undefined也是单独的类型是带有 Javascript 思维,在遇到复杂结构的时候经常会思考遗漏的问题。最重要的就是忽略类型兼容性的问题。
typescript
const temp1: undefined = undefined;
const temp2: null = null;
const temp3: string = null; // 仅在关闭了strictNullChecks时才成立
const temp4: string = undefined; // 仅在关闭了strictNullChecks时才成立
let temp5 = undefined; // any
let temp6: string = null; // 仅在关闭了strictNullChecks时才成立
// 仅在关闭了strictNullChecks时才成立
function getStr(): string {
if (Math.random() > 0.5) {
return null;
}
return "hello";
}
type User = {
name: string;
age: number;
};
function getUser(): User {
if (Math.random() > 0.5) {
return null;
}
return {
name: "John",
age: 30,
};
}