What is a proper way to create a type for Vue props

Viewed 6476

I'm trying to create a custom type for my prop in Vue js, I've created a types folder and added it in the tsconfig.typeRoots the IntelliSense and all the other things work correctly, no issues at compile time but when I visit that component, I get an error that Car is not defined but I have already defined it and it works at other places but after checking official documentation I got to know that prop expects a constructor so I redefined the type to declare class Car and added a constructor prototype but again the same issue.

Here are the files: car component

<script lang="ts">
import Vue from "vue";

export default Vue.extend({
  name: "the-car",
  props: {
    car: {
      required: true,
      type: Car,
    },
  },
});
</script>

the types/common/index.d.ts declaration file

declare class Car {
    name: String;
    image: String;
    kms: Number;
    gears: String;
    desc: String;
    fuel: String;
    engine: String;
    price: Number;
    constructor(name: String, image: String, kms: Number, gears: String, desc: String, fuel: String, engine: String, price: Number);
}
1 Answers

If you mind using Typescript Interface then you can check this post.

In your case, after creating a Car Interface:

props: {
  car: {
    required: true,
    type: Object as () => Car,
  },
},

Edit:

As @Chin. Udara proposed.

If you find validator not getting type inference or member completion isn’t working, annotating the argument with the expected type may help address these problems.

import Vue, { PropType } from 'vue'

const Component = Vue.extend({
  props: {
    car: {
      required: true,
      type: Object as PropType<Car>,
    }
  }
})

Check this Typescript Support docs from Vue.js for more info.

Related