[英]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,
};
}
}
关于如何使用此设置进行验证的任何想法? 还是有更好的方法来定义具有多种类型的道具?
从我对文档的理解来看,需要以下内容:
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,
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.