Skip to content

二、类型声明进阶

一、类型断言

有时候,IDE 或编译器并不能够有效推断出右侧的类型,这时需要我们⼿动 as 声明类型

typescript
let str: string | null 

// 中间做了很多处理,最后 str 被赋值字符串了 

let str2 = str // 这时 IDE 或 编译器可能⽆法推断它究竟是 string 还是 null 类型 

let str3 = str as string // 正确的做法是 as 显式声明它为字符串类型

二、null类型技巧

假设我们现在定义了⼀个可空的字符串

typescript
 let str: string | null

这时为了安全的去使⽤它,我们需要做额外的安全调⽤处理

安全调用

1、⾮空判断

typescript
if (str != null) {
	console.log(str.length) 
}

2、可选链

typescript
console.log(str?.length) // 这⾥表⽰ str 不为 null 时,才接着取 length,否则返回 null

3、⾮空断⾔

typescript
console.log(str!.length) // 与可选链不同的是,这⾥表⽰ str ⼀定不为 null,如果在运⾏时中为 null,会产⽣报错

实际开发过程中,我们应该尽量使⽤第⼀种⾮空判断来处理程序,虽然繁琐,但是最安全的方案

三、其他类型

(1)Date

日期

typescript
const myDate = new Date() 
const myDate1: Date = new Date()

(2)Map

typescript
// key 为 string 类型,value 也是 string 类型 
const map1: Map<string,string> = new Map() 
map1.set('key1', "abc") 

// key 为 string 类型,value 也是 number 类型 
const map2: Map<string,number> = new Map() 
map2.set('key', 1)