(2). TypeScript 配置 —— strictNullChecks配置


一. 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嚴格校驗類型,讓代碼更安全


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM