出现这个问题的主要原因就是没有定义对象类型,解决方法也很简单定义一下对象类型就可以了。
首先可以定义 interface 类型。
interface ComponentConfig {
id: string;
type?: string;
attributes?: object;
component?: string;
items: object[];
listeners?: object[]
dataSet?: object[];
}
interface ConfigType {
[key: string]: PageConfig;
}
import { useRoute } from 'vue-router'
import config from '@/config'
const route = useRoute()
const configTyped: ConfigType = config;
const pageConfig = configTyped[route.name as string] as ComponentConfig;
if (!pageConfig) {
throw new Error('页面配置不存在')
}
如果单独定义 interface 太麻烦,也可以直接定义。
obj: {[key: string]: any[]}
也可以使用更简单的语法糖 Record
。
Record<string, any[]>
定义类型断言。
type EventType = 'click' | 'submit'
强制转换类型为 string。
const key = Object.keys(obj).find((key: string) => Array.isArray(obj[key])) as string