Tho*_*mas 2 typescript vue.js vuejs3 vue-composition-api
作为练习,我尝试在 TypeScript 中定义FontAwesome Vue实现。它们允许icon道具具有不同的类型:
icon: {
type: [Object, Array, String],
required: true
},
Run Code Online (Sandbox Code Playgroud)
我试图给它添加一个验证,但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';
}
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)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)
如果没有验证器,我可以在设置中执行此操作:
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)
Run Code Online (Sandbox Code Playgroud)
关于如何使用此设置进行验证的任何想法?或者有没有更好的方法来定义具有多种类型的道具?
从我对文档的理解来看,需要以下内容:
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
},
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1876 次 |
| 最近记录: |