Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Inheritance TypeScript:将实现的类分配给作为基类键入的变量_Inheritance_Typescript - Fatal编程技术网

Inheritance TypeScript:将实现的类分配给作为基类键入的变量

Inheritance TypeScript:将实现的类分配给作为基类键入的变量,inheritance,typescript,Inheritance,Typescript,我想创建一个基类,其他类将实现和/或扩展它。派生类之所以这样做,是因为它们共享非常相同的功能,但有时对其中的一部分有自己的想法 abstract class Human { constructor(protected _name:string) { } protected identify():string { return this._name; } abstract doTrick():void; } class Boy exte

我想创建一个基类,其他类将实现和/或扩展它。派生类之所以这样做,是因为它们共享非常相同的功能,但有时对其中的一部分有自己的想法

abstract class Human {
    constructor(protected _name:string) {
    }

    protected identify():string {
        return this._name;
    }

    abstract doTrick():void;
}

class Boy extends Human {
    private jump():void {
        console.log("jumping");
    }

    private doTrick():void {
        this.jump();
    }
}
这个很好用。可以创建一个
Boy
,当
identify()
发生时,他会根据
Human
说的话说出自己的名字。问题就在这里:

var person:Human = new Boy("Bob");
我之所以想这样做,是因为我有各种
Human
派生类,我不想做
var person:Boy | Girl | Man | Child | dinogar |随便什么
。问题是这样做会导致错误TS2322:类型“Boy”不能分配给类型“Human”

我觉得我应该能够将
person
键入为
Human
,即使我将派生的
Boy
类分配给它,因为
Boy
类只是
Human
类的一个实现


我遗漏了什么?

你说的是问题所在,但不是问题所在。它不允许这个任务吗?它会给您带来什么错误?我对您的代码唯一的问题是编译器抱怨
Human.doTrick
是公共的,但它在
Boy.doTrick
中是私有的。如果你把它们都改成protected,那就好了。正如@Amy所说的,问题/错误到底是什么?我已经更新了问题以包含错误:错误TS2322:类型“Boy”不可分配给类型“Human”。嗯。奇怪。修复公共vs受保护的问题实际上已经修复了它。我猜这种不匹配导致了实施合同得不到承认。谢谢你的帮助!需要澄清的是,问题不在于合同不被承认,问题在于
男孩的合同与
人的合同不兼容。由于
Human
需要公开可用的
doTrick
-方法,因此具有私有
doTrick
的对象不能满足
Human
的要求。