객체 리터럴: 빠르고 직관적인 생성
객체 리터럴은 중괄호 `{}`를 사용해 간단히 객체를 정의하는 방법입니다. 소규모 데이터나 임시 객체를 만들 때 이상적입니다.
let user = {
id: 1001,
username: "sunny",
isActive: true,
};
console.log(`사용자: ${user.username}, 활성 상태: ${user.isActive}`);
// 출력: 사용자: sunny, 활성 상태: true
생성자 함수: 재사용 가능한 객체 설계
생성자 함수는 `new` 키워드와 함께 호출되어 동일한 구조의 객체를 반복 생성할 수 있습니다. TypeScript에서는 타입 명시로 안정성을 더합니다.
function Task(title: string, due: Date) {
this.title = title;
this.due = due;
this.isDone = false;
}
let task1 = new Task("팀 회의 준비", new Date("2025-03-01"));
console.log(`작업: ${task1.title}, 마감: ${task1.due.toLocaleDateString()}`);
// 출력: 작업: 팀 회의 준비, 마감: 2025. 3. 1
함수 매개변수로 객체 전달
객체를 함수의 매개변수로 전달하면, 해당 함수 내에서 객체의 프로퍼티를 활용할 수 있습니다.
let order = {
product: "이어폰",
quantity: 2,
price: 30000,
};
function calculateTotal(orderInfo: { product: string; quantity: number; price: number }): number {
return orderInfo.quantity * orderInfo.price;
}
console.log(`주문 총액: ${calculateTotal(order)}원`);
// 출력: 주문 총액: 60000원
Object.create(): 프로토타입 기반 생성
Object.create() 메서드는 특정 프로토타입을 상속받는 새로운 객체를 생성할 때 유용합니다. 이를 통해 프로토타입 기반의 상속 구조를 구현할 수 있습니다.
let devicePrototype = {
powerOn(): string {
return "장치가 켜졌습니다.";
},
};
let smartphone = Object.create(devicePrototype);
smartphone.model = "Galaxy";
smartphone.storage = 128;
console.log(`모델: ${smartphone.model}, 용량: ${smartphone.storage}GB`);
console.log(smartphone.powerOn());
// 출력: 모델: Galaxy, 용량: 128GB
// 장치가 켜졌습니다.
클래스를 사용한 객체 생성
클래스는 객체의 설계도를 정의하며, 속성과 메서드를 캡슐화합니다. TypeScript의 접근 제한자와 타입 정의를 활용해 구조적이고 안전한 객체를 생성할 수 있습니다.
class Pet {
constructor(public name: string, private age: number) {}
describe(): string {
return `${this.name}는 ${this.age}살입니다.`;
}
}
let myPet = new Pet("루비", 3);
console.log(myPet.describe());
// 출력: 루비는 3살입니다.
// console.log(myPet.age); // 오류: private 속성은 외부 접근 불가
객체 방법 선택하기
- 객체 리터럴: 간단한 데이터 집합을 생성할 때 적합합니다.
- 생성자 함수: 프로토타입 기반 객체 생성 방식을 사용할 수 있으며, 복잡한 구조의 객체를 만들 때 유용합니다.
- 함수 매개변수로 전달: 객체의 구조를 함수 매개변수로 받아 활용함으로써, 코드의 재사용성과 유연성을 높입니다.
- Object.create(): 특정 프로토타입을 상속받는 객체를 생성하여, 상속 구조를 간편하게 구현할 수 있습니다.
- 클래스: 보다 구조적이고 객체 지향적인 방식으로 객체를 정의하고 생성할 수 있습니다.
'TypeScript' 카테고리의 다른 글
[TypeScript] never 타입 (0) | 2025.02.24 |
---|---|
[TypeScript] unknown 타입 (0) | 2025.02.24 |
[TypeScript] any 타입 (1) | 2025.02.24 |
[TypeScript] 튜플(Tuple): 다양한 타입을 하나로 관리하기 (0) | 2025.02.24 |
[TypeScript] Enum 이해와 활용 (0) | 2025.02.24 |