Vuejs prop validation with multiple types and typed arrays

Viewed 1955

Using Vuejs 3 and Typescript, the goal is to get a prop to be of type string | string[]. Looking at the docs, it looks like I should be able to set a prop using multiple types like so:

props: {
    prop1: {type: [String, Array], default: ""}
}

Looking at a Vetur commit and the docs again, it looks like I should be able to set an array prop type like so:

props: {
    prop1: {type: Array as PropType<string[]>, default: []}
}

I can get both of these to work individually no problem, but when I try to combine them I get an error:

props: {
    prop1: {type: [String, Array as PropType<string[]>], default: ""}
}

No overload matches this call.
The last overload gave the following error.
    Type '{ type: (StringConstructor | (new (...args: any[]) => string[] & object) | (() => string[]) | PropConstructor<string[]>[])[]; default: string; }' is not assignable to type 'PropOptions<unknown, unknown> | (new (...args: any[]) => object) | (() => unknown) | PropConstructor<unknown>[] | null'.
    Types of property 'type' are incompatible.
        Type '(StringConstructor | (new (...args: any[]) => string[] & object) | (() => string[]) | PropConstructor<string[]>[])[]' is not assignable to type 'true | (new (...args: any[]) => object) | (() => unknown) | PropConstructor<unknown>[] | null | undefined'.
        Type '(StringConstructor | (new (...args: any[]) => string[] & object) | (() => string[]) | PropConstructor<string[]>[])[]' is not assignable to type 'PropConstructor<unknown>[]'.
            Type 'StringConstructor | (new (...args: any[]) => string[] & object) | (() => string[]) | PropConstructor<string[]>[]' is not assignable to type 'PropConstructor<unknown>'.
            Type 'PropConstructor<string[]>[]' is not assignable to type 'PropConstructor<unknown>'.
                Type 'PropConstructor<string[]>[]' is not assignable to type '() => unknown'.
                Type 'PropConstructor<string[]>[]' provides no match for the signature '(): unknown'.

I'm not sure what's different between the array syntax for defining types and just using the PropType thing directly, but it's very unhappy about something there. I'm also a bit confused by the unknown stuff mentioned in the error as I would expect everything to be either strings or arrays.

1 Answers

This seems to work:

props: {
    prop1: {type: [Array, String] as PropType<string[] | string>, default: ""}
}

It seems like you have to cast the entire type, otherwise you get the warnings. Also it seems Array defaults to uknown[] type

Related