我创建了一个Vuex模块,并在我的变异中使用一个键将一个对象设置为另一个对象:obj [key] = newobj。我也在这里使用打字稿。
鉴于:
// store state interface
export interface Office {
id: number;
name: string;
zip?: string;
city?: string;
address?: string;
phone?: string;
phone2?: string;
}
export interface Organization {
[key: string]: any;
id: number;
name: string;
offices: { [key: string]: Office };
}
// store action
const setOffice = (state: OrganizationState, item: Office) => {
Vue.set<Office>(state.offices, item.id, item);
// or, it does not change much
Vue.set(state.offices, item.id, item);
};
TypeScript给我一个错误:
25:19 Argument of type '{ [key: string]: Office; }' is not assignable to parameter of type 'Office[]'.
Property 'includes' is missing in type '{ [key: string]: Office; }'.
23 |
24 | const setOffice = (state: OrganizationState, item: Office) =>{
> 25 | Vue.set<Office>(state.offices, item.id, item);
| ^
26 | };
在键入中,有2个版本的Vue.set-一个用于对象,一个用于数组:
// vue/types/vue.d.ts
export interface VueConstructor<V extends Vue = Vue> {
set<T>(object: object, key: string, value: T): T;
set<T>(array: T[], key: number, value: T): T;
}
就我而言,它始终使用array类型。
问题在于您的第二个参数(item.id
)是一个数字,这使调用与第一个重载不兼容,第一个重载期望astring
作为第二个参数。
简单的解决方案是将转换id
到一个string
呼叫:
Vue.set<Office>(state.offices, item.id.toString(), item);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句