TypeScript 之 类型断言、类型转换

69 阅读1分钟

TS 类型断言、类型转换

类型断言语法格式:A 数据类型的变量 as B 数据类型。

let b:B;

let c:C = B as C;

理解:绕过TS编译检查,类型断言就是对编译器说:我就是这个类型了,无需检查。

类型转换是断言的另外一种实现方式,格式为:

let b:B;
let c:C = <C>B

export class Vechile {
  static count: number = 3
  public brand: string // 品牌
  public vechileNo: string // 车牌号
  public days: number // 租赁天数
  public total: number = 0 // 支付的租赁总费用
  constructor(brand_: string, vechileNo_: string, days_: number) {
    this.brand = brand_
    this.vechileNo = vechileNo_
    this.days = days_
  }
  public calculateRent() {
    console.log(this.brand + "车牌号为: " + this.vechileNo + "开始被租");
    return 0;
  }
}

class Car extends Vechile {
  public type: string // 车的型号
  constructor(brand_: string, vechileNo_: string, days_: number, type_: string) {
    super(brand_, vechileNo_, days_)
    this.type = type_
  }

  public getPriceByType() {
    let rentMoneyByDay: number = 0;
    if (this.type === '普拉多巡洋舰') {
      rentMoneyByDay = 800
    } else if (this.type === '凯美瑞旗舰版') {
      rentMoneyByDay = 400
    } else if (this.type === '威驰智行版') {
      rentMoneyByDay = 200
    }
    return rentMoneyByDay;
  }
  // 根据车的型号来获取租用一天该型号车的租金public getPriceByType() [...
  public calculateRent() {
    super.calculateRent()
    console.log("小轿车租赁...")
    return this.days * this.getPriceByType();
  }
}


class Bus extends Vechile {
  public seatNum: number
  constructor(brand_: string, vechileNo_: string, days_: number, seatNum_: number) {
    super(brand_, vechileNo_, days_)
    this.seatNum = seatNum_;
  }

  public getPriceBySeatNum() {
    let rentMoneyByDay: number = 0;

    if (this.seatNum <= 16) {
      rentMoneyByDay = 200
    } else if (this.seatNum > 16) {
      rentMoneyByDay = 1600
    }
    return rentMoneyByDay;
  }
  // 根据车的型号来获取租用一天该型号车的租金public getPriceByType() [...
  public calculateRent() {
    super.calculateRent()
    return this.days * this.getPriceBySeatNum();
  }
}

class Customer {
  rent(vechileNo: Vechile) {
    let car = vechileNo as Car;
    console.log("car.type:" + car.type);

    return vechileNo.calculateRent();
  }
}

let vechile: Vechile = new Car('普拉多巡洋舰', 'A132456', 30, '普拉多巡洋舰');

let car: Car = vechile as Car;
console.log(car.calculateRent());

vechile = new Bus('普拉多巡洋舰', 'A132456', 30, 10);
// let bus: Bus = <Bus>vechile; // 类型转换
let bus: Bus = vechile as Bus; // 类型断言