반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- 로지텍 MX Vertical 마우스
- array method 요약
- for in for of 차이점
- for in 문 예시
- vue scss
- javascript cookie 삭제
- forEach map 차이
- 로컬스토리지 객체 저장
- vscode 초기화
- input range 컬러변경
- 객체 반복문
- 검색창 autofocus
- react 검색 기능 구현
- 로컬스토리지 쓰기 읽기 삭제
- 접근자 함수
- vue sass 사용하기
- react input autofocus
- 접근자 프로퍼티
- input range
- javascript cookie 얻기
- for of 문 예시
- vscode 재설치
- Object for in
- pip 명령 에러
- vue scss 전역 설정
- input type="range"
- next.config.mjs
- javascript cookie 설정
- setter 함수 동기적 실행
- 로지텍 버티컬 마우스 사용 후기
Archives
- Today
- Total
짬짬이기록하기
유니온타입 사용 시 타입 좁히기 본문
반응형
1. typeof는 원시타입만 잡아냄(number, bigint, string, boolean, undefined, null)
2. instanceof 가 객체타입을 잡아낼 수 있다. (Date 같은 내장객체)
type Period = {
start: string,
end: string,
}
function getDayType(day: Period | Date): Date {
if (day instanceof Date) return day
return new Date(day.start)
}
console.log(getDayType(new Date("2024-01-01")))
console.log(getDayType({start: "2025-12-31", end: "2026-01-01"}))
3. 필드 in 객체 : 객체안에 필드가 있는지 여부 판단
4. is : 타입가드함수(리턴이 true이면 변수는 특정타입이다.)
function 타입가드(변수: unknown): 변수 is 특정타입 {
return 조건식;
}
type Rectangle = {width: number, height: number};
type Circle = {radius: number}
// shape is Rectangle : 리턴값이 true이면 shape는 Rectangle 타입이다. false이면 shape는 Rectangle 타입이 아니다.
function isRectangle(shape: unknown): shape is Rectangle {
// shape as Rectangle : shape의 타입이 Rectangle이라면 width의 값이 undefined가 아니다.
return (shape as Rectangle).width !== undefined && (shape as Rectangle).height !== undefined
}
function calculateArea(shape: Rectangle | Circle): number {
if(isRectangle(shape)) {
return shape.width * shape.height
} else {
return Math.PI * shape.radius ** 2
}
}
console.log(calculateArea({ width: 10, height: 5 }));
console.log(calculateArea({ radius: 7 }));
5. type에 식별자를 선언하는 방법
type Track = {
type: "track", //식별자
title: string,
releaseDate: string,
}
type Artist = {
type: "artist", //식별자
name: string,
debutDate: string,
}
const result: Track | Artist = {
type: "track", // 식별자를 지정해서 진정한 Track 또는 Artist가 선언되도록 함
title: "hello",
releaseDate: "2024-01-01"
}
6. exhaustiveCheck 완전성 체크 : 아래와 같이 Radio 타입이 추가되는 경우 에러를 일으켜서 추가 조건을 작성할 수 있도록 가이드함
type SearchResult = Track | Artist | Radio;
type Radio = {
type: "radio",
title: string,
numberOfSong: number,
}
function getTypeName(result: SearchResult) {
if(result.type === "track") return "트랙"
else if(result.type === "artist") return "아티스트"
else if(result.type === "radio") return "라디오"
else {
exhaustiveCheck(result); // else if(result.type === "radio") return "라디오" 해당 구문이 없다면, 여기에서 에러를 발생한다. 개발자가 알아차릴 수 있도록함
return "결과"
}
}
function exhaustiveCheck(param: never) { // never : 절대로 발생할 수 없는 값, 즉 여기에 들어오게 된다면 에러가 있는 것임
throw new Error("error")
}
반응형
'Web Development > Typescript' 카테고리의 다른 글
제네릭 타입 (0) | 2025.06.30 |
---|---|
기타 type 정리 (0) | 2025.06.25 |
type 정의하기 (0) | 2024.12.30 |