인프런 영문 브랜드 로고
인프런 영문 브랜드 로고

인프런 커뮤니티 질문&답변

haruharu님의 프로필 이미지

작성한 질문수

웹 게임을 만들며 배우는 React에 TypeScript 적용하기

useCallback과 keyof, typeof

undefined 처리

작성

·

439

·

수정됨

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;
};

이렇게 가능합니다.
haruharu님의 프로필 이미지

작성한 질문수

질문하기