我创建了一个 Vuex 模块,在我的突变中,我使用一个键将一个对象设置为另一个对象:obj[key] = newobj。我也在这里使用 typescript 。
给定:
// 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
) 是一个数字,这使得调用与第一个重载不兼容,第一个重载需要 string
作为第二个参数.
简单的解决方案是在调用中将 id
转换为 string
:
Vue.set<Office>(state.offices, item.id.toString(), item);
关于typescript - Vue.set - TypeScript 推断的错误类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50151258/