/技术
分类:技术最近更新:2026-04-15浏览:2813
在 js 中,一个 class 只能继承自另一个 class,若其他类中的方法与属性也想继承,则很麻烦。而在 ts 中可以使用 implements 来实现一些类共有方法属性的提取。
typescriptclass Car { switchRadio(trigger: boolean) { } } class cellphone { switchRadio(trigger: boolean) { } }
上述两个类都有一个共同的方法,我们可以使用 interface 接口把他提取出来,implements 实现它。此时 car 和 cellphone 两个类中都需要有 switchRadio 方法,不然会报错。
typescriptinterface Radio { switchRadio(trigger: boolean): void // 注意写法,void表示函数没有返回值 } class Car implements Radio { switchRadio(trigger: boolean) { } } class cellphone implements Radio { switchRadio(trigger: boolean) { } }
新加一个 Battery interface,使 cellphone 类接入而 car 类不接入。
typescriptinterface Battery { checkBatteryStatus(): void; } interface Radio { switchRadio(trigger: boolean): void; // 注意写法,void表示函数没有返回值 } class Car implements Radio { switchRadio(trigger: boolean) { } } class cellphone implements Radio, Battery { // 逗号连接 switchRadio(trigger: boolean) { } checkBatteryStatus() { // 内部方法加上checkBatteryStatus,注意:不能少!!!!! } }
interface 还可以继承,直接用 extends 即可
typescriptinterface Battery { checkBatteryStatus(): void; } interface Radio { switchRadio(trigger: boolean): void; // 注意写法,void表示函数没有返回值 } interface BatterywithRadio extends Radio { checkBatteryStatus(): void; } class Car implements Radio { switchRadio(trigger: boolean) { } } class cellphone implements BatterywithRadio { // 逗号连接 switchRadio(trigger: boolean) { } checkBatteryStatus() { } }