我注入了以下依赖项:
abstract class Person {
age(): void {};
}
class YoungPerson implements Person {
age(): void {
console.log('I am 12');
}
}
class OlderPerson implements Person {
age(): void {
console.log('I am 30');
}
}
class Man {
base: Person
constructor({ base = new YoungPerson() }: { base?: Person } = {}) {
this.base = base;
}
age(): void {
this.base.age();
}
}
const man1 = new Man();
man1.age(); // I am 12
const man2 = new Man({ base: new OlderPerson() });
man2.age(); // I am 30
上面的方法很好。
但是,这也可以...
class Car {
age() {
console.log('Should not be allowed, but it works.')
}
}
const man3 = new Man({ base: new Car() });
man3.age(); // Should not be allowed, but it works.
当Car
类中的base
属性和Man
构造函数参数被定义为类型{{1}时,为什么打字稿允许我传递base
对象}}?
答案 0 :(得分:2)
就TypeScript而言,Car是Person,因为它充当了person(具有正确签名的age方法)。 TypeScript不在乎您是否声明它显式实现某种类型。