ts配置文件中有个选项 "strictNullChecks" 如果设置值为false,那么以下代码都不是问题 ,如果设置为true, 以下代码可以说明undefined和null在ts中的区别
代码语言:javascript复制// 两个空类型
let u: undefined = undefined
let n: null = null
// 常见区别
Number(null) // 0;
Number(undefined) // NaN
let age: number = null
console.log(5 age) // 5;
age = undefined
console.log(5 age) // NaN
console.log(undefined == null) // ture
// 类型检测
let height: number
height = 100 // success
height = '100' // fail
height = undefined // success
height = null // success
let weight: number | undefined
weight = undefined
// ? 相当于string| undefined
function getPeople(name?: string) {
return name || ''
}
getPeople('liuyi')
getPeople(undefined)
getPeople(null) // fail
// any
let school: any
school = null // success
school = undefined // success
school = 'hello' // success
school = 3 // success
let width: number
//width = getWidth()
if (width === undefined) { // fail
}
function getWidth(): number {
if (Math.random() > 0.3) {
return undefined
} else if (Math.random() > 0.6) {
return null
}
return 0
}