Programing

Vue.set - TypeScript로 추론된 잘못된 유형

c10106 2022. 4. 26. 21:31
반응형

Vue.set - TypeScript로 추론된 잘못된 유형

내 돌연변이에 Vuex 모듈을 만들면 오브제[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 | };

여기에 이미지 설명을 입력하십시오.

타이핑에는 Vue.set의 2가지 버전이 있다. 하나는 객체용이고 다른 하나는 어레이용이다.

// 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;
}

내 경우는 항상 타이프 배열을 사용한다.

문제는 당신의 두 번째 파라미터가 (으)라는 것이다.item.id)는 숫자로, 이것은 통화에 대해 예상되는 첫 번째 과부하와 양립할 수 없게 만든다.string제2의 주장으로서

간단한 해결책은 변환하는 것이다.id완전히string요청 시:

Vue.set<Office>(state.offices, item.id.toString(), item);

참조URL: https://stackoverflow.com/questions/50151258/vue-set-wrong-type-inferred-by-typescript

반응형