美文网首页
ts—interscetion Type

ts—interscetion Type

作者: 米诺zuo | 来源:发表于2022-03-09 15:04 被阅读0次

    & 多个类型集合的交集

    | 多个类型集合的并集

    使用type定义

    type Admin = {
      name: string;
      privileges: string[];
    }
    
    type Employee = {
      name: string;
      startDate: Date;
    }
    
    type ElevatedEmployee = Admin & Employee;
    
    

    使用interface定义

    interface Admin {
      name: string;
      privileges: string[];
    }
    
    interface Employee {
      name: string;
      startDate: Date;
    }
    
    interface  ElevatedEmployee extends Admin, Employee{}
    

    使用定义的类型

    let ee: ElevatedEmployee = {
      name:'max',
      privileges:['create-admin'],
      startDate:new Date()
    }
    

    编译后的js

    let ee = {
        name: 'max',
        privileges: ['create-admin'],
        startDate: new Date()
    };
    

    使用type 定义任意类型

    type Combinable = string | number;
    

    typeGuard: 保护代码在运行时不报错

    function printEmployeeInformation(emp: ElevatedEmployee) {
      console.log('name'+ emp.name)
      //判断属性是否存在
      if('privileges' in emp){
        console.log('employee '+ emp.privileges)
      }
      if('startDate' in emp){
        console.log('startDate '+ emp.startDate)
      }
    }
    printEmployeeInformation(ee)
    

    检验对象的某个属性是否存在
    https://dmitripavlutin.com/check-if-object-has-property-javascript/

    // @errors: 2493
    class Car {
      driver(){
        console.log('driving...')
      }
    }
    
    class Truck{
      driver(){
        console.log('driving is truck')
      }
    
      loadCargo(amount: number){
        console.log('loading cargo' + amount)
      }
    }
    
    type Vehicle = Car | Truck;
    const v1 = new Car();
    const v2 = new Truck();
    function useVehicle(vehicle: Vehicle) {
      vehicle.driver();
      if(vehicle instanceof Truck){
        vehicle.loadCargo(1000)
      }
      // if('loadCargo' in vehicle){
      //  vehicle.loadCargo(1000)
      // } 
    }
    useVehicle(v1);
    useVehicle(v2);
    
    //output
    // [LOG]: "driving..." 
    // [LOG]: "driving is truck" 
    // [LOG]: "loading cargo1000"
    

    相关文章

      网友评论

          本文标题:ts—interscetion Type

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