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}