Skip to content

类型细化 ​

类型细化指编译器分析代码结构从而知道表达式的具体类型,细化后的类型通常比其声明的类型更具体,编译器能识别并进行类型细化的代码结构:

  • 类型守卫
  • 可辨识联合类型
  • 赋值语句
  • 流程控制语句
  • 断言函数

类型守卫 ​

类型守卫是能让编译器推断出更具体类型的一类表达式。

ts
// ✨ typeof类型守卫,编译器能根据typeof的结果将x的类型细化为对应类型
function f(x: any) {
  if (typeof x === 'string') {
    console.log('x为string')
  }
}

// ✨ instanceof类型守卫
function f(x: any) {
  if (x instanceof Date) {
    console.log('x为Date')
  }
}

// ✨ in类型守卫
function f(x: object) {
  if ('name' in x) {
    console.log('x存在name属性')
  }
}

// ✨ 逻辑与或非类型守卫
function f(x: object | true | null | 0) {
  if (!x) {
    console.log('x为false或0')
  }
  if (x && x.location && x.location.y) {
    console.log('x.location.y存在')
  }
}

// ✨ 等式类型守卫,===、!==、==、!=
function f(x: any) {
  if (x === undefined) {
    console.log('x为undefined')
  }
}

// ✨ 自定义类型守卫函数
type A = { a: string }
type B = { b: string }
function isTypeA(x: A | B): x is A {
  return (x as A).a !== undefined // 逻辑检查,返回布尔值
}
function f(x: A | B) {
  if (isTypeA(x)) {
    console.log('x为A')
  }
}

// ✨ this类型守卫,类型谓词“x is T”中,x为this时则叫做this类型守卫
// this类型守卫主要用于类和接口中
class Teacher {
  isStudent(): this is Student {
    return false
  }
}
class Student {
  grade: string
  isStudent(): this is Student {
    return true
  }
}
function f(person: Teacher | Student) {
  if (person.isStudent()) {
    person.grade // 编译器能将该分支中的person对象类型细化为Student
  }
}

可辨识联合类型 ​

可辨识联合类型,又称标签联合类型,是种数据结构,常见形式就是对象类型组成的联合类型,每个对象都有一个同名属性,被称为判别式属性,其类型为单元类型,编译器可从可辨识联合类型中推断出对象的属性。

单元类型:只有一个可能值的类型,比如字面量类型、null、undefined 和 void。

ts
type Shape =  
  | { kind: "circle", radius: number } // 圆形特有属性radius  
  | { kind: "square", size: number }   // 正方形特有属性size  
  
function f(x: Shape) {  
  if (x.kind === "circle") { // 编译器能识别出x有kind属性
    console.log(x.radius)    // 编译器能识别出该分支下x有radius属性
  }  
}

赋值语句分析 ​

编译器可分析赋值语句,根据等号右侧操作数的类型去细化左侧操作数的类型。

ts
const x = 100 // x为number

基于控制流的类型分析 ​

编译可从 if 语句、switch 语句、return 语句等流程控制语句中分析类型。

断言函数 ​

断言表示一种判定,TS 引入了断言函数,用于检查实际参数类型是否符合类型判定。

语法:function assert(x): asserts x is T {}
或 function assert(x): asserts x {}

asserts 和 is 是关键字,x 必须是函数参数列表的一个形参,若一个函数带有 asserts 类型判定,则该函数是一个断言函数。

这两种形式的断言函数在断言失败时都必须抛异常,否则 TS 认为断言成立,而异常记得要处理,断言函数在编译时的作用是类型收窄,有助于编译器类型推断。

asserts x is T ​

该形式断言 x 为 T 类型。

ts
function assertIsString(value: any): asserts value is string {
  if (typeof value !== 'string') {
    throw new Error('Value must be a string')
  }
}
function f(input) {
  assertIsString(input) // 断言成功则input被收窄为string类型
  console.log(input.toUpperCase()) // TS知道input是string类型,所以不会报错
}

asserts x ​

该只断言 x 是真值,但不指定具体类型。

ts
function assertTruthy(value: any): asserts value {
  if (!value) {
    throw new Error('Value must be truthy')
  }
}

function f(input) {
  assertTruthy(input) // 断言成功则input被收窄为非空类型
  console.log(input) // TS知道input是真值
}