dmodliba
dmodliba

Reputation: 63

Complex types for properties in defineProps in Vue

In my code I have (or would like) to use complex prop types at some points.Below is an example of what I have in mind:

enum Country {
  [...]
}

interface IPerson {
  firstname: string;
  lastname: string;

}

interface IAddress {
  street: string;
  houseNo: string;
  city: string;
  postalCode: string;
  country: number;
}

interface ITestComponentProps {
  person: IPerson;
  addresses: Array<IAddress>;
}

Then what I want to use this all for in TestComponent.vue is:

[...]
const props = defineProps<ITestComponentProps>();
[...]

what I would expect now is some kind of error message or anything that tells me I have not provided the props in the right structure when trying something like this:

[...]
<TestComponent :props="'foo'" />
[...]

In the documentation for Vue it is stated the following:

Currently complex types and type imports from other files are not supported. It is possible to support type imports in the future.


Does anybody know if there is a workaround to get that desired behavior or when complex types will be supported?

Upvotes: 4

Views: 5205

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

In Vue version < 3.3, the following syntax :

const props = defineProps<ITestComponentProps>();

supports only :

  • A type literal
  • A reference to an interface or a type literal in the same file

It's recommended to use the other syntax :

import {PropType} from 'vue'

const props=defineProps({
       person:{
          type:Object as PropType<Person>
       }
  })

since this syntax :

  • Works in Options API as well as composition API, with or without script setup
  • Is a bit more to type, yes.
  • gives you runtime warnings when passing the wrong (basic) type (i.e. string -instead of number).
  • Works with imported props objects as well.

credit to Linus borg in this comment

Upvotes: 9

Related Questions