代码之家  ›  专栏  ›  技术社区  ›  dlkulp

具有多个类型和类型化数组的Vuejs属性验证

  •  1
  • dlkulp  · 技术社区  · 3 年前

    使用Vuejs 3和Typescript,目标是让道具成为类型 string | string[] . 看着 the docs ,看起来我应该可以使用多种类型设置道具,如下所示:

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

    看着一个 Vetur commit the docs again ,看起来我应该可以设置一个数组属性类型,如下所示:

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

    我可以让这两个单独工作没问题,但当我试图将它们组合起来时,我得到了一个错误:

    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'.
    

    我不确定定义类型的数组语法和只使用 PropType 但我对那里的事情很不满意。我还对错误中提到的未知内容有点困惑,因为我希望所有内容都是字符串或数组。

    1 回复  |  直到 3 年前
        1
  •  2
  •   Shunji Lin    3 年前

    这似乎有效:

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

    看起来你必须强制转换整个类型,否则你会得到警告。似乎也是 Array 默认为 uknown[] 类型