强制一个类与对象的定义必须包含哪些成员
interface MyInterface {
property: type; // 属性
methodName(p1: type, p2: type, ...): type; // 方法
}
- 类使用时可以有额外的成员,对象使用时必须完全相同
class ClassName implements MyInterface { }
class ClassName extends FatherClass implements MyInterface { }
- 类使用接口需要
implements
关键字 - 如果类使用接口后还需要继承,那么
extends
需要在implements
之前
构造器签名
interface Contructor {
new(param: type, ...): InstanceType
}
- 在类定义时,对类的构造方法进行约束
- 对赋值的类进行约束,该类的构造方法,参数和返回实例必须符合
示例
interface ClassI {
name: string;
getName(): string;
}
const user: ClassI = {
name: '狗娃',
getName (): string {
return this.name
}
}
class User implements ClassI {
name:string = '狗娃'
getName (): string {
return this.name
}
}