• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

undefined 처리

23.02.01 02:06 작성 23.02.01 02:11 수정 조회수 315

0

강의에서 computerChoice의 리턴타입에 undefined가 추가되어있는 문제 해결하실때 if() throw new Error(); 사용해서 처리하거나 느낌표(!) 사용하신다했는데 if() throw new Error();로 어떻게 처리하신다는건지 알 수 있을까요? 어떻게 해봐도 해결이 안되네요. ㅠㅠ

 

const rspCoords = {
  바위: '0',
  가위: '-142px',
  보: '-284px',
} as const;

const scores = {
  가위: 1,
  바위: 0,
  보: -1,
} as const;

type imgCoords = typeof rspCoords[keyof typeof rspCoords];

const computerChoice = (imgCoords: imgCoords) => {
  return (Object.keys(rspCoords) as ['바위', '가위', '보']).find(function (v) {
    return rspCoords[v] === imgCoords;
  });
};

답변 1

답변을 작성해보세요.

1

const rspCoords = {
  바위: '0',
  가위: '-142px',
  보: '-284px',
} as const;

const scores = {
  가위: 1,
  바위: 0,
  보: -1,
} as const;

type imgCoords = typeof rspCoords[keyof typeof rspCoords];

const computerChoice = (imgCoords: imgCoords) => {
  const result = (Object.keys(rspCoords) as ['바위', '가위', '보']).find(function (v) {
    return rspCoords[v] === imgCoords;
  });
  if (!result) throw '말도 안돼';
  return result;
};

이렇게 가능합니다.