TypeScript - 타입에러

임보라·2024년 10월 28일

TypeScript

목록 보기
1/1

주로 나타나는 타입에러들을 정리해보니 대부분 기대한타입이 아닌 undefined일 경우의 에러다.
예외처리를 꼭 한 번 더 체크하자.

1. TypeScript가 Set 객체를 반복할 수 없다는 경고

const stampImg = [...new Set(stampList.filter((item) => item.region === list).map((item) => item.stampimg))];
//Set 형식은 --downlevelIteration 플래그 또는 es2015 이상의 --target 을 사용하는 경우에만 반복할 수 있습니다.

tsconfig.json

    "target": "es6",
    "downlevelIteration": true, //이전 버전의 JS로 컴파일할 때, ES6 이상의 반복기능을 사용할 수 있도록(Set, Map, Array 사용가능)

2. 'undefined'일 때 할당불가 경고

if (!stampList) return console.log('데이터가 없습니다.'); //유효성 검사 추가(화면에는 안나오게 console 사용)

3. 컴포넌트가 올바른 JSX 요소 형식이 아니라는 경고

'StampList'은(는) JSX 구성 요소로 사용할 수 없습니다.
해당 '() => void | React.JSX.Element' 형식은 올바른 JSX 요소 형식이 아닙니다.


4. 'string[]' 형식은 'string' 형식에 할당할 수 없습니다.

//BF
const region = decodeURIComponent(params.id);
  • 타입단언추가, params.id문자열로 반환
//AF
const region = decodeURIComponent((params.id as string[]).toString()); 

5. 이 타입형식에 '~~'이 없습니다

  • 호출하는것의 타입 다시보기
//BF
const [stampData, setStampData] = useState<StampDetailPropsType | null>(null);

//AF
const [stampData, setStampData] = useState<StampDetailPropsType[]>([]); //null값 안받고, 기본값도 배열로 변경

6. 이 호출과 일치하는 오버로드가 없습니다.

  • undefined일 수 있다
  • undefined여부 확인 / 예외 처리를 추가
{stampData.map((list) => (
            <li key={list.id} className="flex items-center justify-between">
              <p>{list.address}</p>
              <span>{new Date(list.created_at).toLocaleDateString()}</span> //이 호출과 일치하는 오버로드가 없습니다.
            </li>
          ))}
<span>{list.created_at ? new Date(list.created_at).toLocaleDateString() : 'N/A'}</span>

6-1. 이 호출과 일치하는 오버로드가 없습니다.

  • 존재여부 확인 후 예외처리 추가
//BF
  const oldestDate = stampData.reduce((oldest, current) => {
    const oldestDate = new Date(oldest.created_at);
    const currentDate = new Date(current.created_at);
    return currentDate < oldestDate ? current : oldest;
  }, stampData[0]);

//AF
  const oldestDate = stampData.reduce((oldest, current) => {
    const oldestDate = oldest.created_at ? new Date(oldest.created_at) : new Date();
    const currentDate = current.created_at ? new  Date(current.created_at) : new Date(); //있냐? > 있으면 앞에꺼 없으면 뒤에꺼
    return currentDate < oldestDate ? current : oldest;
  }, stampData[0]);

7. 'undefined' 형식은 'SetStateAction<StampDetailPropsType[]>' 형식에 할당할 수 없습니다.

  • 배열을 기대했지만 undefined일 수 있다.
  • undefined일때 빈배열이 할당되게 수정
//BF
const stampFilterList = res?.filter((item) => item.region === decodedParams);
//AF
const stampFilterList = res?.filter((item) => item.region === decodedParams) || [];

8. SetStateAction 이름을 찾을 수 없습니다.'Dispatch' 이름을 찾을 수 없습니다.

  • setVisit 값을 Prop으로 넘겨줬을때 interface 에서
    setVisit 가 받는 타입을 알림창으로 정의해준다.
    붙여줬을때 Dispatch, SetStateAction은 리엑트 패키지에서 불러와야한다.
import React, { useEffect, useState, Dispatch, SetStateAction } from 'react';

interface StampActivePropsType {
  address: AddressPropsType;
  setVisit: Dispatch<SetStateAction<Boolean>>;
  visit: Boolean;
  stampList: any[] | null | undefined; //TODO: any 추후수정
}

0개의 댓글