[React] TypeScript 오류해결

DaramGee·2025년 6월 17일

TIL

목록 보기
13/17

typeScript 에러

TS2322: Type Mgr[] | undefined is not assignable to type Mgr[]
Type undefined is not assignable to type Mgr[]
RightPanelHeader.tsx(70, 46): The expected type comes from property mgrList which is declared here on type IntrinsicAttributes & { mgrList: Mgr[]; }

TS18048: mgrList is possibly undefined

이유? "정적 타입 단속" 문제(mgrList가 undefined일 가능성이 있음.)

const TeamChangeButton = ({ mgrList }: { mgrList: Mgr[] }) => {  ...  } 

해결방식

🔹방법 1. mgrList가 항상 undefined 아님을 보장할 수 있다면

호출하는 쪽에서 안전하게 mgrList!로 non-null assertion 처리해줘 but, 확실할 때만 사용하기

<TeamChangeButton mgrList={mgrList!} />

🔹방법 2. mgrList가 undefined일 수도 있다면, 타입을 허용하고 기본값 설정

const TeamChangeButton = ({ mgrList = [] }: { mgrList?: Mgr[] }) => {  ... }

🔹방법 3. 컴포넌트 타입을 전체 Props 인터페이스로 정의해서 가독성 높이기

interface TeamChangeButtonProps { mgrList?: Mgr[]; }  
const TeamChangeButton = ({ mgrList = [] }: TeamChangeButtonProps) => { ...}

방법 2로 하고, 화면 리턴되는 부분에서도 유무 값 확인 추가하여서 이슈 해결


0개의 댓글