12

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?

1 Answer 1

39

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.

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.