(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