美文网首页
类型别名 type 与 interface

类型别名 type 与 interface

作者: RickyWu585 | 来源:发表于2021-12-13 09:42 被阅读0次
    • interface可以用来定义行为(函数)
    interface discount {
      (price: number): number;
    }
    let cost: discount = function (price: number): number {
      return price * 0.8;
    };
    
    • interface 可以重复定义,会自动合并
    interface User {
      name: string
      age: number
    }
    
    interface User {
      sex: string
    }
    
    /*
    User 接口为 {
      name: string
      age: number
      sex: string 
    }
    */
    
    • interface和type都可以扩展类型别名
    1. interface通过extends继承实现
    // 接口扩展接口
    interface PointX {
      x: number;
    }
    
    interface Point extends PointX {
      y: number;
    }
    
    1. type通过&交叉类型实现
    type PointX = {
      x: number
    }
    
    type Point = PointX & {
      y: number
    }
    
    • interface 在这种情况下无法替代 type
      type FavoriteNumber = number | string
    • interface 也没法实现 Utility type
    • Utility type 用法:
      用泛型给它传入一个其他类型,然后Utility type对这个类型进行某种操作。例如:
    type Person = {
      name: string
      age: number
    }
    
    const xiaoMing: Partial<Person> = {name: 'xiaoming'} 
    //不报错,partial代表部分类型
    
    const shenMiRen:Omit<Person,'name' | 'age'> = {}
    // omit代表删除某个类型,这里的值不能出现 name 和 age 属性了
    
    type NewPerson = Pick<Person, 'name'>
    // Pick作用是挑选一个对象里的某些属性,变成一个新的类型
    
    type PersonKeys = keyof Person
    // 这里的类型(keyof返回的)是一个联合类型:'name' | 'string' 
    type Age = Exclude<PersonKeys,'name'>
    // 这里的类型只有一个age,Exclude与Omit不同,过滤的是联合类型里的类型
    
    • Partial实现
    type Partial<T> = {
      [P in keyof T]?: T[P]
    }
    
    • Exclude实现:这里的 T extends U,是针对T类型的遍历,这个T是个联合类型,
      遍历这个联合类型,符合U,就never,不符合,就返回出来
    type Exclude<T,U> = T extends U ? never : T
    
    • Omit实现
    type Omit<T,K extends keyof any> = Pick<T,Exclude<keyof T,K>>
    

    相关文章

      网友评论

          本文标题:类型别名 type 与 interface

          本文链接:https://www.haomeiwen.com/subject/itjdfrtx.html