Typescript学习--Null 和 Undefined

默认情况下,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

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值