johnsoncodehk / vue-tsc

vue-tsc --noEmit && vite build
https://www.npmjs.com/package/vue-tsc
MIT License
241 stars 6 forks source link

Error passing class from data to child component via prop #32

Closed bwolf closed 3 years ago

bwolf commented 3 years ago

I don't understand the error message from vue-tsc with following code, which is basically passing a variable from a parent component to a child component. The parent component create an instance of a (custom) class and keeps the variable in its data(). Within the template it uses the child component and passes the variable to it (prop).

I think my description is a bit hard to follow. Here is a minimal example where the README contains the relevant extract of the topic: https://github.com/bwolf/error-vue-tsc-data-class-instance/blob/master/README.md

Any idea what is here the problem? Thanks

johnsoncodehk commented 3 years ago

@pikax I think this is defineComponent problem, could you take a look?

<template>
  <!-- store should be BoringComp type, but it's {} type -->
  {{ store }}
</template>

<script lang="ts">
import { defineComponent } from 'vue'

class BoringComp {
  constructor(private items: { name: string }[]) { }
}

export default defineComponent({
  data() {
    return {
      store: new BoringComp([])
    }
  },
})
</script>
pikax commented 3 years ago

Yes it caused by the unwrapping of properties, when you return an object through data it will be unwrapped (aka remove .value) , on this step a new equivalent type is created.

In this particular case BoringComp is equivalent to {} since it does not expose any value or method.

If the class is really important you may mark it as raw:

defineComponent({
  data() {
    return {
      store: markRaw(new BoringComp([]))
    }
  },
  mounted() {
    this.store // currently doesn't work, but it should
  }
})

In that case @bwolf do you mind opening an issue on vue-next and I can sort that out

pikax commented 3 years ago

just PRed a fix for that https://github.com/vuejs/vue-next/pull/3791

When using classes is recommended to markRaw on the instance

johnsoncodehk commented 3 years ago

@pikax Thanks for your reaction!