Typescript中undefined与null的区别

ts配置文件中有个选项  "strictNullChecks"  如果设置值为false,那么以下代码都不是问题 ,如果设置为true, 以下代码可以说明undefined和null在ts中的区别

1// 两个空类型 2let u: undefined = undefined 3let n: null = null 4 5// 常见区别 6Number(null) // 0; 7Number(undefined) // NaN 8 9let age: number = null 10console.log(5 + age) // 5; 11 12age = undefined 13console.log(5 + age) // NaN 14 15console.log(undefined == null) // ture 16 17// 类型检测 18let height: number 19height = 100 // success 20height = '100' // fail 21height = undefined // success 22height = null // success 23 24 25let weight: number | undefined 26weight = undefined 27 28// ? 相当于string| undefined 29function getPeople(name?: string) { 30 return name || '' 31} 32 33getPeople('liuyi') 34getPeople(undefined) 35getPeople(null) // fail 36 37// any 38let school: any 39school = null // success 40school = undefined // success 41school = 'hello' // success 42school = 3 // success 43 44let width: number 45//width = getWidth() 46 47if (width === undefined) { // fail 48 49} 50function getWidth(): number { 51 if (Math.random() > 0.3) { 52 return undefined 53 } else if (Math.random() > 0.6) { 54 return null 55 } 56 return 0 57}
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

SpringBoot自定义序列化的使用方式

场景及需求:项目接入了SpringBoot开发,现在需求是服务端接口返回的字段如果为空,那么自动转为空字符串。例如:\    {        "id":1,        "name":null    },    {        "id":2,        "name":"x