默认情况下,null 和 undefined 是其它类型的子类型,可以赋值给其它类型,如number类型,此时,赋值后的类型会变成 null 或 undefined。比如:
let u: undefined = undefined;
let n: null = null;
然而,当你指定了–strictNullChecks标记,null和undefined只能赋值给void和本身对应的类型。比如:
// 启用 --strictNullChecks
let x: number;
x = 1; // 运行正确
x = undefined; // 运行错误
x = null; // 运行错误
如果在某处你想传入一个 string或null或undefined,你可以使用联合类型string | null | undefined。比如:
// 启用 --strictNullChecks
let x: number | null | undefined;
x = 1; // 运行正确
x = undefined; // 运行正确
x = null; // 运行正确
–strictNullChecks标记的启用是在tsconfig.json文件里进行配置。
{
"compilerOptions": { //编译选项,可以被忽略,这时编译器会使用默认值
"strictNullChecks": false, //在严格的null检查模式下,null和undefined值不包含在任何类型里,只允许赋值给void和本身对应的类型。
}
}
具体的tsconfig.json文件配置请戳:https://www.tslang.cn/docs/handbook/tsconfig-json.html