处理函数实现
interface IParent {
name: string;
print(): void;
}
class Child1 implements IParent {
name: string;
private extraProp1: number;
constructor(name: string, extraProp1: number) {
this.name = name;
this.extraProp1 = extraProp1;
}
print() {
console.log(`Child1 - Name: ${this.name}`);
}
}
class Child2 implements IParent {
name: string;
constructor(name: string) {
this.name = name;
}
print() {
console.log(`Child2 - Name: ${this.name}`);
}
static staticMethod() {
console.log('Child2 static method');
}
}
function handle(parent: IParent) {
// 仅处理IParent接口中定义的属性和方法
parent.print();
console.log(`Name: ${parent.name}`);
// 如果需要处理Child1特有的私有属性,这种处理是不被允许直接访问的,因为私有属性只能在类内部访问
// 如果需要处理Child2特有的静态方法,由于传入的是实例,静态方法无法通过实例调用,需要通过类名调用
// 所以这里只能处理IParent接口的内容
}
TypeScript类型兼容性规则
- 接口实现兼容性:在TypeScript中,只要类实现了接口中定义的所有属性和方法,就满足类型兼容性。
Child1
和Child2
都实现了IParent
接口中的name
属性和print
方法,所以它们的实例可以作为参数传递给handle
函数,即使Child1
有私有属性,Child2
有静态方法,这些额外的部分不影响接口兼容性。
- 私有属性兼容性:私有属性(如
Child1
中的extraProp1
)仅在类的内部可见。TypeScript的类型系统在检查兼容性时,不会因为类中有私有属性而影响其与接口的兼容性,但外部代码无法直接访问这些私有属性。
- 静态成员兼容性:静态成员(如
Child2
中的staticMethod
)不属于实例的类型范畴。接口只描述实例的属性和方法,所以静态方法不会影响类与接口的兼容性。在handle
函数中,传入的是实例,不能直接调用静态方法,需要通过类名(如Child2.staticMethod()
)调用静态方法。