为什么实例是兼容的,即使它们的类构造函数不兼容?

问题描述 投票:0回答:1

在以下示例中,

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?
typescript
1个回答
0
投票

Type A 与 Type B 兼容告诉您 Type A 的实例可以用作实例类型 B。这意味着该实例必须支持可能对其他类型执行的所有操作(即具有必要的属性)和方法)。

Employee 支持您可能对 Person 执行的所有操作,因此它可以分配给 Person 变量。

不兼容的构造函数不会改变这一点,因为这不是类的“实例”必须允许的操作。您不会在“Person”或“Employee”对象上调用构造函数。

© www.soinside.com 2019 - 2024. All rights reserved.