热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

在Typescript中,一个方法只能存在于子类中吗?-InTypescript,canamethodexistonlyonasubclass?

Ihaveaninheritancehierarchyinatypescriptapplicationthatresemblesthefollowing:我在typescr

I have an inheritance hierarchy in a typescript application that resembles the following:

我在typescript应用程序中有一个类似于以下内容的继承层次结构:

class A {
   someProp: any;

   constructor(someObj: any){
   }
}


class B extends class A {
    constructor(someObj: any){
        super(someObj); 
    }

    public doStuff(){
        console.log("doing stuff!");
    }
}

In a second file, I attempt to call methods on the subclass after instantiating it like so:

在第二个文件中,我尝试在实例化之后调用子类上的方法,如下所示:

var instanceB: A;
...
instanceB = new B(someObj);
instanceB.doStuff(); // produces error symbol cannot be resolved, it is probably located in an inaccessible module

So what am I doing wrong? As far as I understand prototypal inheritance in Javascript, the method will be searched for in the hierarchy of regardless of where it is defined.

那么我做错了什么?据我所知,Javascript中的原型继承,无论在何处定义,都将在层次结构中搜索该方法。

As a workaround, I've added an abstract method in the base class, and then I provide the implementation in the subclass. The problem with this is that I need to be able to swap one subclass for another depending on the application state. And to me, it seems unnecessary to define a method on the parent class that all subclasses need not implement.

作为一种解决方法,我在基类中添加了一个抽象方法,然后我在子类中提供了实现。这个问题是我需要能够根据应用程序状态将一个子类交换为另一个子类。对我来说,似乎没有必要在父类上定义一个所有子类都不需要实现的方法。

1 个解决方案

#1


This doesn't work because you define instanceB to be of type A and not the subtype B.

这不起作用,因为您将instanceB定义为类型A而不是子类型B.

You can execute methods that belong to B, if instanceB is indeed an instance of B, by using a type guard:

通过使用类型保护,您可以执行属于B的方法,如果instanceB确实是B的实例:

var instanceB: A;
...
instanceB = new B(someObj);
if (instanceB instanceof B) {
    instanceB.doStuff(); // no more error
}

Or by casting instanceB to be of type B:

或者通过将instanceB转换为B类:

// no more error, but will throw an error when instanceB is not B
( instanceB).doStuff();

推荐阅读
author-avatar
风铃草549天王
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有