Search code examples
typescriptvue.jsvue-componentabstract-class

How to create and extend a abstract class component in VueJS?


how are u doin?

So, i've been working in a new project for the company where I work.

We are going to develop a SDK to give to our third-party developers classes so they can build components to run in our application.

I want to write an ABSTRACT CLASS so I could force the developers to implement some methods.

How can I do this?

I was thinking about create a PURE TYPESCRIPT CLASS to build the ABSTRACT CLASS and then inherit it in my COMPONENT CLASS...

Something like:

abstract class AbstractClass {
  public abstract abstractMethod(): void
}

But how can I make this work with a vue component class?


Solution

  • vue-class-component can be used to define Vue components as TypeScript classes but it has a limitation regarding abstract classes.

    Depending on how abstract methods are supposed to be used, additional checks can be added to enforce their implementation in children components, e.g.:

    interface IFooComponent {
      bar(): void;
    }
    
    @Component({})
    class BaseFooComponent extends Vue {
      ['bar' as string]()  {
        throw new Error('not implemented');
      }
    }
    
    // `implements` causes compilation error
    class FooComponent extends BaseFooComponent implements IFooComponent {
      // bar() {}
    
      mounted() {
        this.bar(); // causes both compilation and runtime error
      }
    }