类实现接口(implements)
TypeScript 也能够用接口来明确的强制一个类去符合某种契约。
即 接口可以约束类有哪些成员及其属性。
-
类实现接口时,必须实现接口中声明的所有成员。
// 类实现接口 interface Human { name: string; eat(): void; } class Man implements Human { constructor(name: string) { this.name = name; } name: string; eat() {} sleep() {} // 可以增加自己的方法 }
-
接口只描述了类的公有成员(public),它不会帮你检查类是否具有某些私有成员。
class Man implements Human { constructor(name: string) { this.name = name; } private name: string; eat() {} sleep() {} } // error! 属性'name'在'Man'中是私有的,但在'Human'中不是.
-
接口不能约束构造函数,为什么呢?
类具有两个类型:静态部分的类型和实例部分的类型。当一个类实现一个接口时,只对其实例部分进行类型检查。 constructor 存在于类的静态部分,所以不在检查的范围内。interface I { new (): void; } class C implements I { constructor() {} } // error! 类'C'错误的继承了接口'I'。
接口继承接口(extends)
接口可以相互继承,并且一个接口可以继承多个接口。
interface Human {
name: string;
eat(): void;
}
interface Child {
cry(): void;
}
interface Boy extends Human, Child {}
let boy: Boy = {
name: "",
eat() {},
cry() {},
};
接口继承类
当接口继承了一个类类型时,它会继承类的成员但不包括其实现。
即 抽象出类的结构,没有具体实现。
class Auto {
state: number = 0;
}
interface AutoInterface extends Auto {}
class C implements AutoInterface {
state: number = 1;
}
class MyAuto extends Auto implements AutoInterface {}
接口会继承到类的 public
、private
和 protected
成员。因此,当你创建的接口继承了拥有 私有/受保护成员 的类时,它只能被 该类或其子类 实现(implements)。
class Auto {
private state: number = 0;
}
interface AutoInterface extends Auto {}
class C implements AutoInterface {
state: number = 1;
} // error! 'state' 在 AutoInterface 是私有成员,而在 C 中不是
class MyAuto extends Auto implements AutoInterface {} // ok!
总结
TypeScript 入门系列
- Hello TypeScript(01)-- 环境搭建
- Hello Typescript(02)-- 枚举类型
- Hello Typescript(03)-- 对象类型接口
- Hello Typescript(04)-- 函数类型接口、混合类型接口、类接口
- Hello Typescript(05)-- 函数
- Hello Typescript(06)-- 类
- Hello Typescript(07)-- 类与接口的关系
- Hello Typescript(08)-- 泛型
- Hello Typescript(09)-- 类型推断、类型兼容性、类型保护
- Hello Typescript(10)-- 交叉类型、联合类型、索引类型、映射类型、条件类型