代码之家  ›  专栏  ›  技术社区  ›  ThomasReggi

子级定义此变量的抽象类

  •  0
  • ThomasReggi  · 技术社区  · 7 年前

    我想用打字稿 abstract class 并强制实现在它可以使用的类中定义函数/变量。

    abstract class Animal {
      sound: string;
      speak() {
        console.log(this.sound);
      }
    }
    
    class Cat extends Animal {
      sound = 'meow';
    }
    
    const c = new Cat()
    c.speak()
    

    sound 应该是的必需属性 Cat 也会继承 speak 来自动物。

    这样的事情有可能吗?

    是的,我需要 抽象类 即使在这个例子中并不明显。

    2 回复  |  直到 7 年前
        1
  •  0
  •   Przemyslaw Jan Beigert    7 年前

    abstract sound: string

    abstract class Animal {
      abstract sound: string;
      speak() {
        console.log(this.sound);
      }
    }
    

    example

        2
  •  -1
  •   ThomasReggi    7 年前

    abstract

    abstract class Animal {
      abstract sound: string;
      speak() {
        console.log(this.sound);
      }
    }
    
    class Cat extends Animal {
      sound = 'meow';
    }
    
    const c = new Cat()
    c.speak()
    
    推荐文章