为什么TypeScript允许注入无效类型?

时间:2020-09-11 12:19:29

标签: typescript dependency-injection

我注入了以下依赖项:

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对象}}?

1 个答案:

答案 0 :(得分:2)

就TypeScript而言,Car是Person,因为它充当了person(具有正确签名的age方法)。 TypeScript不在乎您是否声明它显式实现某种类型。