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);
}
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.