首页 > 解决方案 > 如何为打字稿类的抽象方法定义模板?

问题描述

当我们在 TypeScript 中创建一个抽象类时,它就像:

export abstract class Test {
    abstract anAbstractMethod(): void;
    public aPublicMethod(): void {}
}

...然后当我们用它扩展一些类时:

export class TestSon extends Test {
    anAbstractMethod(): void {
        throw new error('Method not implemented!');
    };
}

创建它throw new error('Method not implemented!');是为了帮助我们不要忘记实现它的代码。我不知道是 VSCode 做到了还是它是预定义的 TypeScript 东西。

有谁知道如何将此行更改为其他代码。如果我们可以为每个抽象方法定义一个模板,告诉下一个程序员或多或少应该将什么编码到方法中,而不是仅仅依赖于注释,那将是非常好的......

标签: typescriptabstract-classtypescript3.0

解决方案


但是......如果你想要预定义的代码,你不应该使用抽象类吗?需要时,可以重写或不重写抽象类方法。

abstract class Test {
    aMethod(): void {      
      console.log("not yet implemented")
    }
    anotherMethod(): void {      
      console.log("not yet implemented")
    }
}

class TestSon extends Test {
   anotherMethod(){
     console.log("this is implemented")
   }
}

let s = new TestSon()
s.aMethod()
s.anotherMethod()

推荐阅读