웹사이트 검색

타입스크립트: 결합된 타입에 속성이 존재하지 않음?


다음 추상화된 TS 시나리오:

interface EmotionsOkay {
  emotion: string;
  okay: "yap";
}
interface EmotionsNotOkay {
  emotion: string;
}
type UndetereminedEmotion = EmotionsOkay | EmotionsNotOkay;
const areYouOkay = (test: UndetereminedEmotion) => {
  console.log(test.okay ? "happy :D" : "sad D:");
};

콘솔에 test.okay를 기록할 때 존재하지 않는 것처럼 보여 Type스크립트 오류를 발생시킵니다.

Property `okay` does not exist on type `UndetereminedEmotion`.

비록 그것이 충분히 존재할 수 있더라도, 메서드에 전달된 테스트가 EmotionsOkay 타입이라면.

왜 이런 일이 일어나는 거죠?

답변 #1

이 시점에서 TS는 그것이 어떤 타입인지 알지 못합니다. 그것이 EmotionsOkay일 수도 있어 모든 것이 괜찮을 수 있고, 아니면 EmotionsNotOkay일 수도 있어 okay 속성이 존재하지 않을 수 있습니다. 이것이 바로 이 오류가 발생하는 이유입니다. 어떤 타입인지 확인해야 합니다.

이를 확인하기 위해 in 키워드를 사용할 수 있습니다.

interface EmotionsOkay {
  emotion: string;
  okay: "yap";
}
interface EmotionsNotOkay {
  emotion: string;
}
type UndetereminedEmotion = EmotionsOkay | EmotionsNotOkay;
const areYouOkay = (test: UndetereminedEmotion) => {
  console.log('okay' in test && test.okay ? "happy :D" : "sad D:");
};

처음부터 okay 속성이 없으면 행복할 수 없습니다.

만약 이 경우에 instanceof를 사용할 수 없는 이유가 궁금하다면, 이 질문을 확인해 보세요

여기에 놀이터가 있습니다

답변 #2

타입스크립트 타입 단언(다른 언어의 캐스팅과 유사)을 사용할 수 있습니다.

interface EmotionsOkay {
  emotion: string;
  okay: "yap";
}
interface EmotionsNotOkay {
  emotion: string;
}
type UndetereminedEmotion = EmotionsOkay | EmotionsNotOkay;
const areYouOkay = (test: UndetereminedEmotion) => {
  console.log((test as EmotionsOkay).okay ? "happy :D" : "sad D:");
  // or
  console.log((<EmotionsOkay>test).okay ? "happy :D" : "sad D:");
};

관련기사