원시 타입
원시 타입은 단일 값으로, 불변성을 특징으로 합니다.
- number: 정수와 실수를 포함
- string: 텍스트 데이터
- boolean: 참/거짓 논리값
- null/undefined: 값 없음 또는 미정의 상태
- symbol: 고유 식별자
- bigint: 큰 정수 처리
// status.ts
const userId: number = 101;
const userNickname: string = "은비";
const isLoggedIn: boolean = true;
const sessionKey: symbol = Symbol("session");
const largeCount: bigint = 1234567890123456n;
const lastLogin: null = null;
console.log(`${userNickname} (ID: ${userId}) - 로그인: ${isLoggedIn}`);
객체 타입
객체 타입은 여러 값이나 함수를 포함할 수 있는 복합적인 데이터 구조입니다. 배열, 튜플, 열거형, 함수, 클래스, 인터페이스 등이 객체 타입에 속하며, 이러한 구조들은 가변성을 가집니다.
// product.ts
// 배열: 상품 이름 목록
const productNames: string[] = ["셔츠", "바지", "모자"];
// 튜플: 상품 정보 (이름, 가격)
const featuredItem: [string, number] = ["청바지", 59000];
// 함수: 할인 가격 계산
function applyDiscount(price: number, discount: number): number {
return price * (1 - discount);
}
// 열거형: 상품 상태
enum ProductStatus {
InStock = "재고 있음",
OutOfStock = "품절",
OnOrder = "주문 중",
}
const itemStatus: ProductStatus = ProductStatus.InStock;
// 클래스와 인터페이스: 상품 상세
interface ProductDetails {
name: string;
price: number;
}
class ShopItem implements ProductDetails {
constructor(public name: string, public price: number, private stock: number) {}
getStockInfo(): string {
return `${this.name} - 재고: ${this.stock}개`;
}
}
const shirt = new ShopItem("티셔츠", 25000, 10);
console.log(shirt.getStockInfo()); // "티셔츠 - 재고: 10개"
고급 데이터 타입
TypeScript는 단순한 타입 정의를 넘어서, 복잡한 데이터 모델링을 지원합니다.
- 유니온 타입: 한 변수에 여러 타입 중 하나의 값이 할당될 수 있도록 합니다.
- 교차 타입: 여러 타입을 결합하여 하나의 타입으로 정의, 모든 조건을 만족해야 합니다.
- 리터럴 타입: 변수에 특정 값만 할당할 수 있도록 강제합니다.
- 매핑된 타입: 기존 타입의 속성을 변형하여 새로운 타입을 생성합니다.
// order.ts
// 유니온
let identifier: number | string = 1001;
identifier = "ID_1001";
// 교차
interface Shipping {
address: string;
}
interface Payment {
amount: number;
}
type Order = Shipping & Payment;
const orderDetails: Order = { address: "서울시 중구", amount: 45000 };
// 리터럴
type DeliveryMethod = "express" | "standard";
const shippingMethod: DeliveryMethod = "express";
// 매핑
interface OrderInfo {
id: number;
customer: string;
}
type ReadOnlyOrder = {
readonly [K in keyof OrderInfo]: OrderInfo[K];
};
const lockedOrder: ReadOnlyOrder = { id: 1, customer: "지훈" };
// lockedOrder.id = 2; // 오류: 읽기 전용
console.log(`주문 ${lockedOrder.id}: ${orderPayment}, ${shippingMethod}`);
'TypeScript' 카테고리의 다른 글
[TypeScript] 문자열 다루기 (0) | 2025.02.21 |
---|---|
[TypeScript] 정밀한 숫자 처리 (0) | 2025.02.21 |
[TypeScript] 변수와 스코프 (0) | 2025.02.21 |
[TypeScript] 시작하기 (0) | 2025.02.21 |
[TypeScript] 타입으로 강화된 JavaScript (0) | 2025.02.21 |