강의

멘토링

커뮤니티

Inflearn Community Q&A

gogosssing950908's profile image
gogosssing950908

asked

Applying TypeScript to React while learning while making web games

useCallback and keyof, typeof

undefined 처리

Written on

·

473

·

Edited

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

Answer 1

1

zerocho님의 프로필 이미지
zerocho
Instructor

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

이렇게 가능합니다.
gogosssing950908's profile image
gogosssing950908

asked

Ask a question