TS之交叉类型

101 阅读1分钟

Itersection Types交叉类型(交集)

使用符号 &

  • 使用:
    • 交叉类型常用于有交集的类型A、B
    • 如果 A、B无交集
      1. 可能得到 never
      2. 也可能只是属性为 never
    type A = string & number // 相当于  type A = never

type中使用

type Person = { name: string; age: number }
type Student = { subjects: string }

type X = Person & Student

interface中使用

interface Colorful {
    color: string
}
interface Circle {
    reaius: number
}
type ColorfulCircle = Colorful & Circle

同名属性求交集

  1. 属性冲突未报错
     type A = {
     id: string
     name: string
     }
     type B = A &  {
     id: number
     email: string
     }
     // 属性 id 冲突, 未报错
     // 得到 id为 never 类型
    
    type A = { kind: 'A', name: string }
    type B = A & { kind: 'B', name: string }
    // 相当于 type B = never
    
  2. 属性冲突报错
    interface Person { 
        id: string
        name:string
    }
    interface User extends Person {
        id: number // 报错,不能将 number 分配给 string
    }
    

方法求交集

  • 对方法求交集,方法的参数为并集, 如下
type A = { method: (a: number) => void }
type B = A & { method: (a: string) => void }
const b: B = {
    method(a){
        console.log(a) // a的类型是 number | string
    }
}