haykou
haykou

Reputation: 387

How to type a Vue.component using typescript?

I have an util function that reset all data content of some Vue component.

export function resetData(vm: any) {
  Object.assign(vm.$data, vm.$options.data.call(vm));
}

And I'm trying to remove the "any" type of my Vue.component, is it possible? There are any Interface that target $data from Vue?

I need to get this type:

enter image description here

Upvotes: 2

Views: 1333

Answers (1)

Daniel Santos
Daniel Santos

Reputation: 15788

Note that the resetData function require a Vue Instance parameter

In this case imports Vue from the "vue" package and use it as a type

import Vue from "vue";

export function resetData(vm: Vue) { ... }

Vue object has $data and $options parameters as expected.

The remaining problem is to know what the object $options.data holds. Once data is a not know type but we are using it as a function, in other words: ()=>void. Or else it will raise a syntax error.

Object.assign(vm.$data, (vm.$options.data as ()=>void).call(vm));

The final code with no compilations errors will be like

import Vue from "vue";
export function resetData(vm: Vue) {
    Object.assign(vm.$data, (vm.$options.data as ()=>void).call(vm));
}

The code becomes a little verbose but now is well tight on its own typing

Upvotes: 1

Related Questions