Props typing in Vue.js 3 with TypeScript
You should use it with PropType
imported from vue like Object as PropType<FlashInterface>
:
import FlashInterface from '@/interfaces/FlashInterface';import { ref,PropType, defineComponent } from 'vue';import { useStore } from 'vuex';export default defineComponent({ props: { message: { type: Object as PropType<FlashInterface>, required: true } }, setup(props) { // Stuff }});
Note : you should create your component using defineComponent
in order to get the types inference.
The compiler is complaining about missing a reference for a (custom) constructor during type checking (links to legacy docs but works the same way with the most recent version of Vue).
In Typescript, you might want to think of interfaces as a contract that an entity should conform to, so they aren't really a constructor, and therefore, we need to provide an implementation of those interfaces.
Since you are on Typescript, if you need to keep the interface, consider using the class equivalent:
// Name the constructor whatever you like,// but I would personally prefix interfaces with an "I"// to distinguish them with the constructorsclass Flash implements FlashInterface { level: string; message: string; id?: string constructor() { // Be sure to initialize the values for non-nullable props this.level = ''; this.message = ''; }}export default { name: 'Home', props: { message: Flash }}
An excerpt from the doc:
In addition,
type
can also be a custom constructor function and the assertion will be made with aninstanceof
check. For example, given the following constructor function exists:
props: { message: { type: function Person(firstName, lastName) { this.firstName = firstName this.lastName = lastName } }}
And of course, another alternative would be as suggested in the other post with PropType
. Either one will do. It's just a matter of preference, I guess.