티스토리 뷰

서버에서 전달받은 데이터를 props로 넘겨서 v-for를 돌렸다. 그런데 자꾸 item이 unknown이라고 빨간줄을 그으며 분노하신다... diarys는 객체 배열인데 정확히 어떤 데이터가 오는지 몰라서 분노하신 것 같다... 그만하세요 타스 선생님 제발......😫

'item' is of type 'unknown'.

 

...
// diarys는 객체 배열인 props이다.
props: {
diarys: Array,
},


...
// 정확한 item의 타입을 몰라 분노하는 것으로 추정
<DiaryItem
  v-for="item in diarys"
  :key="item.date"
  :level="item.level"
  :date="item.date"
  :reason="item.reason"
/>

 

interface를 선언해서 as 키워드로 타입을 정해줘봤다.

// 타입 선언
interface DiaryItemType {
  date: string;
  reason: string;
  level: number;
}

...
// as 키워드로 DiaryItemType[]라는 타입을 지정해줘봤다.
props: {
diarys: Array as DiaryItemType[],
},


...
<DiaryItem
  v-for="item in diarys"
  :key="item.date"
  :level="item.level"
  :date="item.date"
  :reason="item.reason"
/>

바로 아니라고 props에 빨간줄이 그어진다.

Conversion of type 'ArrayConstructor' to type 'DiaryItemType[]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
Type 'ArrayConstructor' is missing the following properties from type 'DiaryItemType[]': pop, push, concat, join, and 28 more.

 

 

챗지피티에게 물어본 결과 함수 형태로 정해주니 화를 잠재우셨다.

interface DiaryItemType {
  date: string;
  reason: string;
  level: number;
}

...
// as 키워드와 같이 함수의 리턴값을 넘겨줬다.
props: {
diarys: Array as () => DiaryItemType[],
},


...
<DiaryItem
  v-for="item in diarys"
  :key="item.date"
  :level="item.level"
  :date="item.date"
  :reason="item.reason"
/>
이는 배열을 할당하더라도 그 배열이 DiaryItemData의 구조를 갖도록 보장한다는 것을 TypeScript에 표시하는 방법입니다.

이 접근 방식은 API에서 가져온 데이터를 처리하는 경우 TypeScript에 데이터의 정확한 유형을 결정하기에 충분한 정보가 없을 수 있는 경우에 유용할 수 있습니다. 

 Array as () => DiaryItemData[] 구문은 추가 컨텍스트를 제공해야 하거나 데이터의 정확한 유형을 TypeScript에서 직접 추론할 수 없는 경우에 자주 사용됩니다.

 

왜 그렇게 사용했는지 물었는데 vue에서 props를 받는 원리와 연관이 되어있는 것 같다. props를 vue 문법을 사용해서 받는 것이라 Array의 ArrayConstructor type에 맞춰 정해줘야해서 그런게 아닐까 추측하고 있다..🤔

 

 

 

이렇게 정해줬더니 부모 컴포넌트에서도 빨간줄이 그어져서 부모 컴포넌트에도 타입을 정해줬다.

// 부모 컴포넌트
const diarys = ref(data as DiaryItemType[]);
728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
글 보관함