Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js + Typescript: How to set @Prop type to string array?

What's the correct way to set the type attribute of the @Prop decorator to Array<string>? Is it even possible?

I'm only able to set it to Array without string like so:

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';

@Component
export default class MyComponent extends Vue {
  @Prop({ type: Array, default: [] }) private readonly myProperty!: string[];
}
</script>

When I try to change it to Array<string> or even string[] I receive the following error:

Argument of type '{ type: boolean; default: never[]; }' is not assignable 
to parameter of type 'PropOptions<any> | Constructor | Constructor[] | undefined'.

Types of property 'type' are incompatible. Type 'boolean' is not assignable to type 
'(new (...args: string[]) => Function) | (() => any) | (new (...args: never[]) => any) | Prop<any>[] | undefined'.

This error message confuses me even more: why is the type now recognised as boolean?

like image 759
winklerrr Avatar asked Mar 02 '26 22:03

winklerrr


1 Answers

Adding the type assertion as PropType<string[]> helps in this case:

<script lang="ts">
import { PropType } from "vue"
import { Component, Prop, Vue } from 'vue-property-decorator';

@Component
export default class MyComponent extends Vue {
  @Prop({
    type: Array as PropType<string[]>, // use PropType
    default: () => [] // use a factory function
  }) private readonly myProperty!: string[];
}
</script>

Source: docs regarding @Prop annotation.

Also note that default Arrays and Objects should always be returned from factory functions (source). This avoids (accidentally) sharing a property among several component instances.

like image 147
mori Avatar answered Mar 05 '26 23:03

mori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!