首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用索引签名扩展类

使用索引签名扩展类
EN

Stack Overflow用户
提问于 2019-04-18 22:30:47
回答 1查看 52关注 0票数 0

我正在尝试创建一个抽象类,但事情并不像我希望的那样工作,而且我担心我的typescript知识是有限的,因为我认为这是一个相当通用的用例。

我有一个抽象的类程序。这个抽象类有一堆函数和属性。

代码语言:javascript
复制
abstract class Program {
  someString: string = "bob";
  someFunc(): void {
    return;
  }
  someOtherfunc: void {
    this.childFunc();
    return; 
  }
}

我还有一个接口'IProgram‘,看起来像这样

代码语言:javascript
复制
interface IProgram {
  childFunc: () => void; 
}

class Child扩展了class Program,也实现了'IProgram‘接口

代码语言:javascript
复制
class Child extends Program implements IProgram {
  childFunc(): void {
    console.log("Hello World")
  }
}

因此,我不能让它工作,而不是得到某种破坏(IMHO)行为。

我已经尝试添加一个索引签名到‘程序’的工作,我没有得到TS错误,但然后一切工作在子程序。我不在乎在IProgram中丢失验证,因为这是不会改变的,但我不希望儿童程序能够去:

代码语言:javascript
复制
this.bob = 'potato'; //TS wont give an error because of index signature in parent

我还尝试在抽象类中将'childFunc‘声明为类型any,但随后它抱怨说它应该是一个函数,而不是成员。我声明它的另一个问题是,我的实现'IProgram‘的子类将不再被强制实现'childFunc’,因为TS在头部中找到了它。

我还做了一个最小的stackBlitz重现这个问题

https://stackblitz.com/edit/typescript-po7hbo

我基本上只想让抽象类接受它的所有子类都将声明这些函数/属性。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-18 22:49:27

看起来您确实希望Program的所有具体子类都实现IProgram,因为您在Program的定义中引用了this.childFunc()。如果是这样,您应该声明Program实现IProgram,在Program中声明childFunc方法,并在Program中声明mark it as abstract

代码语言:javascript
复制
abstract class Program implements IProgram {

  abstract childFunc(): void; // marked as abstract

  someString: string = "bob";
  someFunc(): void {
    return;
  };
  someOtherfunc(): void {
    this.childFunc(); // okay now
    return;
  };  
}

// you can remove the "implements IProgram" from Child since the parent has it
class Child extends Program {
  childFunc(): void {
    console.log("Hello World")
  }
}

抽象方法是在它们的抽象类中声明的,但没有实现,所有具体的子类都必须实现它们,否则会出现错误:

代码语言:javascript
复制
class Oops extends Program { // error!
//    ~~~~ 
// Non-abstract class 'Oops' does not implement inherited 
// abstract member 'childFunc' from class 'Program'.
}

希望这能有所帮助。祝好运!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55748232

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档