ts-node执行文件报错
来源:7-4 【TS类型断言、转换应用】 类型断言的9种使用场景 2

小生来也
2022-08-21
为什么我用ts-node去执行这个文件,结果报错说study不是一个function呢?
1回答
-
这个问题要解释起来——对于前端同学来说,理解会比较复杂,因为涉及到了后端语言多态的思想,需要看完本章多态后来理解会好不少。
首先父类变量断言成子类,虽然能在编译期间获取到子类的方法,但要想运行期间是否还能访问这个方法,取决于父类对象变量指向的是否是一个子类对象,如果是,运行期间就可以访问的到。就是你这样定义:let p:Parent=new Son() 然后再转成 (p as Son).子类独有方法,这样就没问题了。
那你会问,这样做有什么意义了,意义如下:
2. 父类断言成子类本身的真实应用: 一般会结合多态,泛型一般在大厂 koa,nestjs等 Nodejs 服务器大中后端项目中用到, 可大幅提升项目的可扩展性和代码质量。举例【这是个真实项目的代码片段,代码较多,需要耐心看懂思路,对日后开发大中项目会很受益!标注S94行的代码就是把父类断言成子类的行代码】
// 汽车租赁
class Vechile {
static count: number = 3;
public brand: string;// 品牌
public vechileNo: string;// 车牌号
public days: number;// 租赁天数
public total: number = 0;// 支付的租赁总费用
public deposit: number;// 押金
constructor(brand_: string, vechileNo_: string, days_: number, deposit_: number) {
// 赋值......
}
// 计算租赁车的价格 ( calculateRent)
public calculateRent() {
console.log(this.brand + " 车牌号为:" + this.vechileNo + "开始被租");
return 0;
}
}
// 子类Car类 独有属性为type_
class Car extends Vechile {
// public brand: string = "nobrand"
public type: string;//车的型号
constructor(brand_: string, vechileNo_: string, days_: number,
deposit_: number, type_: string) {
// Vechile.call(this,brand_, vechileNo_, days_, total_, deposit_)
super(brand_, vechileNo_, days_, deposit_);
this.type = type_;
}
public calculateRent() {//方法重写 [override]
// 具体业务代码省略....
return 3
}
// 子类独有的方法-检查是否超重
public checkIsWeigui(isOverWeight: boolean) {
if (isOverWeight) {
this.total = this.total + 500;//租金加500
}
}
}
class Bus extends Vechile {
public seatNum: number // 座位数
constructor(brand_: string, vechileNo_: string, days_: number,
deposit_: number, seatNum_: number) {
super(brand_, vechileNo_, days_, deposit_);//使用父类的构造函数的好处
this.seatNum = seatNum_;
//.....
}
public calculateRent() {// 重写了父类的方法
// 具体业务代码省略....
return 10
}
// 子类独有的方法-检查是否超载
public checkIsOverNum(isOverWeight: boolean) {
if (isOverWeight) {
this.total = this.total + 2000;//租金加2000
}
}
}
class Truck extends Vechile {
ton!: number // 座位数
constructor(brand_: string, type_: string,
days_: number, deposit_: number, ton_: number) {
super(brand_, type_, days_, deposit_);
this.ton = ton_;
//.....
}
checkIsOverWeight(isOverWeight: boolean) {
if (isOverWeight) {
console.log("超载了");
this.total = this.total + 2000;
}
}
public calRent() {
// ......
return 100
}
}
class Customer {
// 多态在koa服务器后端大中项目中的使用
// 父类的引用接受不同类的子类对象
rentVechile(vechile: Vechile) {
vechile.calculateRent();//
if (vechile instanceof Vechile) {
// 父类对象变量断言成子类后,调用子类独有方法
(vechile as Bus).checkIsOverNum(true) // S94
}
}
}
let cust = new Customer()
cust.rentVechile(new Car("本田", "京G113", 35, 400, "1"))
cust.rentVechile(new Bus("大巴", "京G115", 89, 700, 16))
032022-08-22
相似问题