具有多种类型的 Vue3 TypeScript 道具

Vue3 TypeScript props with multiple types

作为练习,我尝试在 TypeScript 中定义 FontAwesome Vue 实现。他们允许 icon 道具有不同的类型:

icon: {
    type: [Object, Array, String],
    required: true
},

我试图向它添加验证,但设置中的 props 似乎损坏了:

validator: (prop) => {
    if (typeof prop === 'object') {
        const obj = prop as any;
        return (obj.prefix && obj.iconName);
    } else if (Array.isArray(prop) && prop.length === 2) {
        return true;
    }
    return typeof prop === 'string';
}
Property 'icon' does not exist on type 'Readonly<{ [x: number]: string; } & { length?: number | undefined; toString?: string | undefined; toLocaleString?: string | undefined; concat?: string[] | undefined; join?: string | undefined; slice?: string[] | undefined; ... 16 more ...; flat?: unknown[] | undefined; }> | Readonly<...>'.
Property 'icon' does not exist on type 'Readonly<{ [x: number]: string; } & { length?: number | undefined; toString?: string | undefined; toLocaleString?: string | undefined; concat?: string[] | undefined; join?: string | undefined; slice?: string[] | undefined; ... 16 more ...; flat?: unknown[] | undefined; }>'.Vetur(2339)

没有验证器,我可以在设置中这样做:

setup(props) {
    let icon: Icon; // simple interface I defined having prefix and iconName
    if (typeof props.icon === 'object') {
        icon = props.icon as Icon;
    } else if (Array.isArray(props.icon) && props.icon.length === 2) {
        icon = {
            prefix: props.icon[0],
            iconName: props.icon[1],
        };
    } else if (typeof props.icon === 'string') {
        icon = {
            prefix: 'l',
            iconName: props.icon as string,
        };
    }
}

关于如何使用此设置进行验证的任何想法?还是有更好的方法来定义具有多种类型的道具?

根据我的理解,docs 需要如下内容:

import { defineComponent, PropType } from 'vue'

interface Icon {
  src: string
  width: number
  height: number
}

const Component = defineComponent({
  props: {
    icon: {
        type: [Object, Array, String] as PropType<Icon | Icon[] | string>,
        required: true
    },
  }
})

您可以将其转换为类型。

{
    name: 'Bob' as string | number,
}