8

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);
}
2
  • Hi, I think you need to import the index.d.ts file in the component. Commented Jun 7, 2021 at 3:42
  • @YashMaheshwari I've already added an entry in the tsconfig.json and type checking works well without importing Commented Jun 7, 2021 at 4:49

1 Answer 1

33

type declaration such as type: Car or type: Object as Car will not work because in Vue, it provides additional functionality like prop validation which goes beyond the standard type checking that you get in Typescript.

While type: Object as () => Car will work, the proper way to handle this is by using Vue's helper method PropType.

import { PropType } from 'vue'

props: {
  car: {
    type: Object as PropType<Car>,
    required: true,
  },
},

Check this Typescript Support docs (v2)(v3) from Vue.js for more info about annotating props.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.