【TS】类和接口

super

如果子类覆盖父类中的定义的方法,在子类中可以使用super调用父类中的同名方法。super有两种调用方法:

  • 方法调用:

如:super.onCreate();

  • 构造方法调用:
  • 如:constructor() { super(); }

接口

接口是一种命名类型的方式,这样就不用在行内定义了。

类经常当作接口使用:

class App extends BMMultiWindowPage {
    aWindow: Window;
    cWindow: Window;
    aRouter: StackRouter;
    cRouter: StackRouter;
}

类型别名和接口的异同

类型别名和接口是同一概念的两种句法(类似于函数表达式和函数声明之间的关系)。

  • 两个声明都定义结构,且可以相互赋值:
import { type } from "os";
type Car = {
    wheel: string;
    price: number;
    color: string;
}

let car1: Car = {
    wheel : "baoma",
    price : 30,
    color : "red"
}
interface NewCar {
    wheel: string;
    price: number;
}

let newCar2 :NewCar = car1;
console.log(newCar2);

 //print:{ wheel: 'baoma', price: 30, color: 'red' }

可以看到,当我们把Car类型的car1赋值给NewCar类型的newcar2时,自动扩展出了属性color。

但是我们在接口中添加Car类型中没有的属性则会报错:

以上操作反之亦然。

  • 可扩展性:

对于type

type Car = {
    wheel: string;
    price: number;

}

type NewCar = Car & {
    color: string;
}

这里需要注意 用 & 相当与在Car中添加了color: string;而使用 | 则相当于在Car中添加了color?: string;

对于接口:

interface Car  {
    wheel: string;
    price: number;

}

interface NewCar extends Car {
    color: string;
    wheel: string;
}

这里就相当于type的&,所有的属性都必须要有。

不同之处:

  1. 类型别名更加通用,右边可以时任何类型,而接口只能是结构
  2. 同一作用域中的同名接口会自动合并,而类型别名则会报错
  3. 扩展接口是TS将检查扩展的接口是否可赋值给被扩展的接口,而类型别名则会尽可能地把被扩展的类型和扩展的类型组合在一起,最终结果是重载签名,而不会报错

声明合并

同一作用域中的同名接口会自动合并:

interface Car  {
    wheel: string;
    price: number;

}

interface Car {
    color: string;
    wheel: string;
}

let NewCar2: Car = {
    wheel: "baoma",
    color: "red",
    price: 10
}
console.log(NewCar2);

//print:{ wheel: 'baoma', color: 'string;', price: 10 }

使用泛型:

使用泛型就不可以了,即便是同名。

猜你喜欢

转载自blog.csdn.net/niuguobao/article/details/126214909