Vue 저장소 어레이 선언의 "Not assignable to type never" TS 오류
이 에러가 발생하는 이유를 알 수 없습니다.
'{ id: string; }' 형식의 인수는 'never' 형식의 매개 변수에 할당할 수 없습니다.
...선상에서const index = state.sections.findIndex((section) => section.id === id);
Vue 스토어의 다음 부분에 있습니다.
import { MutationTree, ActionTree, GetterTree } from 'vuex';
interface section {
id: string;
section_header: string;
section_body: string;
sectionItems: any;
}
interface sections extends Array<section>{}
export const state = () => ({
sections: [
{
id: '1',
section_header: 'lorem',
sectionItems: []
},
{
id: '2',
section_header: 'ipsum',
sectionItems: []
}
]
});
type EditorState = ReturnType<typeof state>;
export const mutations: MutationTree<EditorState> = {
ADD_SECTION_ITEM(state, id) {
const index = state.sections.findIndex((section) => section.id === id);
const sectionItem = {
id: randomId()
}
state.sections[index].sectionItems.push(sectionItem);
},
};
값의 유형(이 경우 함수의 반환 값)을 지정하지 않으면 TypeScript는 가능한 한 정확한 유형으로 범위를 좁힙니다.반환된 객체가sections
아이템 어레이는 항상 비어 있습니다.이것에 의해, 다음과 같이 추측됩니다.never[]
(type[]
의 에일리어스입니다.Array<type>
값을 포함할 수 없는 배열입니다.이것은, 다음의 스니펫으로 확인할 수 있습니다.
const functionReturningEmptyArray = () => ({ items: [] });
type EmptyArray = ReturnType<typeof functionReturningEmptyArray>;
// type EmptyArray = { items: never[] }
이 문제를 해결할 수 있는 한 가지 방법은section
반환 유형을 지정하기 위해 작성한 인터페이스state
.
export const state = (): { sections: Array<section> } => ({
sections: [
{
id: '1',
section_header: 'lorem',
sectionItems: []
},
{
id: '2',
section_header: 'ipsum',
sectionItems: []
}
]
});
첫 번째 줄의 빈 괄호 뒤에 있는 콜론은 함수의 반환 유형을 지정합니다.이 경우 오브젝트 타입은 속성이1개밖에 없기 때문에 인라인을 그렸습니다만,state
가독성만을 중시하는 경우는, 다른 타입으로 추출해, 그것을 반환 타입으로서 참조할 수 있습니다.
interface MyState {
sections: Array<section>;
}
export const state = (): MyState => ({
sections: [
{
id: '1',
section_header: 'lorem',
sectionItems: []
},
{
id: '2',
section_header: 'ipsum',
sectionItems: []
}
]
});
이 시점에서 TypeScript는 반환된 값에 오류를 발생시킵니다. 왜냐하면 이 값은section
interface는 오브젝트에도 다음 명령어가 있어야 함을 지정합니다.section_body
반품된 물건에 누락된 물건sections
이것을 수정하려면 , 배열내의 각 오브젝트에, 다음의 어느쪽인가를 지정할 수 있습니다.section_body
속성이 존재하거나 존재하지 않을 수 있다는 사실과 일치하도록 인터페이스를 수정한다.
interface section {
id: string;
section_header: string;
section_body?: string;
sectionItems: any;
}
이제 스토어에 오류가 없지만 더 많은 유형의 안전성을 확보해야 합니다.sectionItems
속성을 변경할 수도 있습니다.any
로.Array<any>
또는 섹션 항목이 어떻게 표시되는지 미리 알고 있는 경우 보다 구체적인 개체 유형을 사용합니다.
필요하신 것 같아요state.sections.push(sectionItem)
대신state.sections[index].sectionItems.push(sectionItems)
.
제 생각에 당신은 아마도 당신의 섹션을 타이핑해야 할 것 같습니다.항목:
interface SectionItem {
id: string
}
interface Section {
id: string;
section_header: string;
section_body?: string;
sectionItems: SectionItem;
}
interface State {
sections: Section[]
}
export const state = (): State => ({
sections: [
{
id: '1',
section_header: 'lorem',
sectionItems: []
},
{
id: '2',
section_header: 'ipsum',
sectionItems: []
}
]
});
type EditorState = ReturnType<State>;
export const mutations: MutationTree<EditorState> = {
ADD_SECTION_ITEM(state, id) {
const index = state.sections.findIndex((section) => section.id === id);
const sectionItem = {
id: randomId()
}
state.sections[index].sectionItems.push(sectionItem);
},
};
왜냐하면 섹션의 유형을 지정하지 않은 경우항목, 타이프스크립트 섹션 보기현재 상태에서 초기화된 항목([]과 동일)으로, 이 배열에 포함되어야 하는 요소의 유형을 식별할 수 없습니다.
그러니까 네가 정의해또한 section_body는 모든 예제에 포함되어 있지 않기 때문에 옵션이어야 합니다.인터페이스명은, 타이프 스크립트로 대문자로 할 필요가 있습니다.
또한 섹션 인터페이스는 필요 없다고 생각합니다.인터페이스의 배열로 입력하는 경우는 string []와 같이 section []를 사용합니다.
마지막으로, 이것은 당신에게 달렸습니다만, 인터페이스(및 일반적으로 코드)에서 다른 명명 규칙을 사용하지 않는 것이 좋습니다.section_body는 snake_case 및 section입니다.아이템은 camel Case 입니다.보통 1개를 고수하고 모든 코드로 유지하는 것이 좋습니다.
편집: 상태를 설명하는 인터페이스 상태를 사용하여 "상태"를 입력해야 합니다.
또한 Vuex에 대한 구체적인 경험은 없지만, Vuex에 대한 구체적인 사용 방법을 나타내고 있는 것 같습니다.이것과는 다릅니다.vuex docs는 이쪽입니다.
언급URL : https://stackoverflow.com/questions/70475907/not-assignable-to-parameter-of-type-never-ts-error-in-vue-store-array-declarat
'itsource' 카테고리의 다른 글
함수는 C에서 구조 변수를 실제로 어떻게 반환합니까? (0) | 2022.08.14 |
---|---|
약속의 then()을 커밋하면 Vuex3 변환이 작동하지 않음 (0) | 2022.08.14 |
VueJs, 계산된 자산과 감시자의 차이점? (0) | 2022.08.14 |
Rubaxa-Sortable이 'Element'에서 'matches'를 실행하지 못했습니다. '>*'는 올바른 선택기가 아닙니다. (0) | 2022.08.14 |
Junit 테스트에서 기본 Spring-Boot application.properties 설정을 덮어씁니다. (0) | 2022.08.14 |