在以下示例中,
constructor
不兼容,但它们的实例是兼容的。为什么?
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
class Employee {
name: string;
age: number;
salary: number;
constructor(name: string, age: number, salary: number) {
this.name = name;
this.age = age;
this.salary = salary;
}
}
const pCtor: typeof Person = Employee; // error, constructors are not compatible
const p: Person = new Employee("", 0, 0); // but the instances *are* compatible, how is that possible?
Type A 与 Type B 兼容告诉您 Type A 的实例可以用作实例类型 B。这意味着该实例必须支持可能对其他类型执行的所有操作(即具有必要的属性)和方法)。
Employee 支持您可能对 Person 执行的所有操作,因此它可以分配给 Person 变量。
不兼容的构造函数不会改变这一点,因为这不是类的“实例”必须允许的操作。您不会在“Person”或“Employee”对象上调用构造函数。