一. emptyType 空類型
// 兩個空類型
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) // true
二. 類型檢測
// 類型檢測
let height: number
height = 100 //success
height = '100' // fail
height = undefined //success
height = null //success
三. 其他類型
let weight: null | undefined
weight = undefined
// ?相當於 string | undefined
function getPeople(name?: string){
return name || ''
}
getPeople('wangrong') //正確
getPeople(undefined) //正確
getPeople(null) //錯誤
// any (不建議使用any)
let school: any
school = null //success
school = undefined //success
school = 'hello' //success
school = 8 //success
總結: undefined 和 null 兩個空類型的設計,使用上不方便,所以 通過strictNullChecks嚴格校驗類型,讓代碼更安全