Search code examples
typescriptvue.jsvue-class-components

vue-class-component & Mixins


I use vue-class-component with TypeScript for my Vue project. I have the component and the Mixin for it:

// MyComp.vue
import Component, { mixins } from 'vue-class-component'
import MyMixin from './mixin.ts'

@Component
export class MyComp extends mixins(MyMixin) {
  compValue: string = 'Hello';
}


// mixin.ts
import Vue from 'vue'
import Component from 'vue-class-component'

@Component
export default class MyMixin extends Vue {
  created() {
    console.log(this.compValue); // TS2339: Property 'compValue' does not exist on type 'MyMixin'.
  }
}

It works, but TypeScript complains about missing Property 'compValue'. How to fix this problem?


Solution

  • The error happens because compValue doesn't exist in MyMixin. In case this is abstract class that is never instantiated on its own and it's guaranteed the property is there, it can be declared:

    export default class MyMixin extends Vue {
      compValue: string;
      created() {
        console.log(this.compValue);
      }
    }