선택적 속성 사용하기: undefined 에러 해결

wldls·2023년 10월 5일
0

TypeScript

목록 보기
3/4

Product 타입이 필요한 모든 곳에서 동일한 타입을 재사용할 수 있으므로 코드의 일관성과 유지보수성이 향상됩니다.
따라서 아래와 같이 types.ts 파일에서 Product 타입을 수정하는 과정에서 발생한 에러의 기록 목적으로 작성되었습니다

ProductPropsType은 원래의 Product 타입과 몇 가지 필드(quantity, option, options)가 누락되어 있습니다.
만약 이 두 타입이 서로 호환되어야 한다면, 누락된 필드를 선택적으로 추가해주는 것이 좋습니다. 즉, 해당 필드들이 항상 존재한다는 보장이 없기 때문에 TypeScript에서 선택적(optional) 속성으로 아래와 같이 추가하였습니다

type ProductPropsType = {
  id: string;
  image?: string;
  title: string;
  category: string;
  price: number;
  options?: Array<string>; 
  quantity?: number; 
  option?: string; 
};

🚨 수정 이후 에러 발생

ERROR

ERROR 
TS18048: 'current.quantity' is possibly 'undefined'.

이전

  const totalPrice =
    products &&
    products.reduce(
      (prev, current) =>
        prev + (current.price ? current.price : 0) * current.quantity,
      0,
    );

이후
->

const totalPrice =
  products &&
  products.reduce(
    (prev, current) =>
      prev + (current.price ? current.price : 0) * (current.quantity || 0),
    0,
  );

quantity 필드가 선택적(optional)으로 선언되었기 때문에, 이 필드는 undefined일 수 있습니다. 따라서 TypeScript는 quantity 필드를 사용할 때마다 이 값이 존재하는지 확인하도록 요구합니다.

두 코드 모두에서 에러가 발생한 부분은 products.reduce() 함수 내부입니다. 여기서 current.quantity를 바로 사용하려 하지만, TypeScript는 이 값이 항상 존재한다는 것을 보장할 수 없으므로 에러를 발생시킵니다.

이 문제를 해결하기 위해선 current.quantity가 존재하는지 확인한 후 사용해야 합니다
(current.quantity || 0) 부분은 quantity가 undefined일 경우 대신에 0을 사용하도록 합니다

profile
다양한 변화와 도전하는 자세로

0개의 댓글