카카오 테크 블로그에서 본 내용을 정리해두려고 쓰는 글.
in 키워드// in 키워드 사용
function printInfo(content: Webtoon | WebNovel) {
if ("isFinish" in content) {
// isFinish 가 있으니 이건 Webtoon 이다.
console.log(content.isFinish); // ✅ OK - content: Webtoon
} else {
console.log(content.age); // ✅ OK - content: WebNovel
}
}
// Tagged Union Types
interface Webtoon {
type: "webtoon";
title: string;
episode: number;
isFinish: boolean;
}
interface WebNovel {
type: "webNovel";
title: string;
episode: number;
age: "all" | 12 | 15 | 19;
}
interface SF {
type: "sf";
title: string;
episode: number;
price: 3000;
}
function printInfo(content: Webtoon | WebNovel | SF) {
switch (content.type) {
case "webtoon":
return content.isFinish; // ✅ OK - content: Webtoon
case "webNovel":
return content.age; // ✅ OK - content: WebNovel
case "sf":
return content.price; // ✅ OK - content: SF
}
}
// 예시 1
function assert(value: any, errorMsg: string): asserts value {
if (!value) throw new Error(errorMsg);
}
function toString(value?: number) {
assert(value !== undefined, "value 는 undefined 가 아니어야 한다.");
return value.toFixed(2);
}
// 예시 2
function getNickname(name: string | null): string {
assert(name != null) // true
return name // string
}
getNickname('fronttigger') // fronttigger
https://velog.io/@songjj77/typescript-타입스크립트-팁들from-Medium
이미 썼던 내용이라 링크로 대체
참조
https://www.fronttigger.dev/2022/typescript/type-guard
https://fe-developers.kakaoent.com/2021/211012-typescript-tip/#4-타입-가드-활용하기