typescript - Vue.set - TypeScript 推断的错误类型

标签 typescript vue.js vuex

我创建了一个 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 | };

enter image description here

在打字中有 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/

相关文章:

javascript - Vuex 中的状态初始化代码应该放在哪里?

javascript - 如何在 ionic 3 中实现 LinkedIn 登录?为什么 Linked In Login 不起作用?

Angular Material 在某些组件中不起作用

javascript - typescript 转译中断

javascript - 用 arrayBuffer 录制 mp3

vue.js - Vue 3 Composition API 在多个组件中重用

javascript - 在 Vuex Store 中构建状态

javascript - Vue Typescript 组件库 - 使用 Webpack 和 SASS

javascript - 状态变化时更新谷歌图表 - vuex

javascript - 如果组件中有 getter,如何更改 v-overlay 的值?