For a challenge, I am currently attempting to characterize the implementation of FontAwesome Vue in TypeScript. The icon prop in this implementation can have various types:
icon: {
type: [Object, Array, String],
required: true
},
I tried to incorporate validation for it, but encountered an issue with props in setup:
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)
Even without the validator, I am able to do this in the setup:
setup(props) {
let icon: Icon; // a simple interface I created with 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,
};
}
}
Do you have any suggestions on how I could implement the validation within this setup? Or perhaps there is a more efficient way to define a prop with multiple types?