객체 타입 (Object Types)
TypeScript에서는 객체의 구조(Shape)를 타입으로 정의할 수 있다.
각 속성(property)의 이름과 타입을 명시하면, 객체가 올바른 형태를 갖도록 보장할 수 있다.
ts
// 자동차 객체
let car: {
make: string;
model: string;
year: number;
};
car = {
make: "Volkswagen",
model: "Tiguan",
year: 2020,
};
💡 객체 타입을 통해
- 객체의 형태/구조를 보장하고 예측 가능하게 만든다.
(make
,model
,year
의 타입이 강제된다.) - 예상치 못한 값이나 속성이 들어가는 것을 방지한다.
1. 기본 객체 타입 정의
객체 타입은 아래와 같이 속성명: 타입
형태로 정의한다.
더 복잡한 경우는 인터페이스(interface) 또는 타입 별칭(type alias)을 사용한다.
ts
{
property_name: property_type;
}
1-1. 객체 리터럴 타입
한 변수에 한정된 구조를 직접 명시하는 방법이다.
ts
// monitor 객체의 타입 명시
let monitor: {
brand: string;
price: number;
};
// 객체 리터럴 할당
monitor = {
brand: "LG",
price: 100,
};
// property에 직접 값 할당
monitor.brand = "LG";
monitor.price = 100;
monitor.displaySize = "22inch"; // 오류: 정의되지 않은 프로퍼티
1-2. 인터페이스 (Interface)
재사용 가능한 객체 타입을 정의할 때 사용한다. extends
를 활용해 확장도 가능하다.
ts
interface Monitor {
brand: string;
price: number;
}
let monitor: Monitor = {
brand: "LG",
price: 120,
};
1-3. 타입 별칭 (Type Alias)
type 키워드로 별칭을 정의해 재사용한다. 인터페이스와 비슷하지만, 유니온/튜플/프리미티브도 표현할 수 있다.
ts
type UserType = {
id: string;
name: string;
age: number;
};
let user1: UserType = { id: "1", name: "Bin", age: 30 };
// 오류: age 누락
let user2: UserType = { id: "2", name: "Park" };
// 오류: 정의되지 않은 속성 포함
let user3: UserType = { id: "3", name: "Binny", email: "email@email.com" };
배열로도 활용 가능하다.
ts
let users: UserType[];
users.push(user1);
users.push(user2);
// 오류: 빈 객체
users.push({});
// 오류: 프로퍼티가 부족한 객체를 넣음
users.push({
id: "10",
});
1-4. 타입 추론
객체를 초기화하면 TypeScript가 구조를 자동으로 추론한다.
ts
let monitor: {
brand: "LG";
price: 120;
};
monitor.price = "123"; // 오류: number에 string 할당 불가
monitor.displaySize = "22inch"; // 오류: 존재하지 않는 프로퍼티
2. 객체의 Property 타입
2-1. 선택 속성 (Optional)
속성이 필수가 아닐 때 ?
를 붙인다.
ts
let user: {
id: string;
name: string;
age?: number; // 선택적 속성
};
user = {
id: "1234",
name: "Binny",
}; // age 없음 → 가능
age
는 선택 속성이기 때문에 user 객체에 age 프로퍼티가 없어도 오류가 발생하지 않는다.
2-2. 읽기 전용 속성 (Readonly)
수정되면 안 되는 속성은 readonly
를 사용한다.
ts
interface Config {
readonly clientKey: string;
url: string;
}
let config: Config = {
clientKey: "abc123",
url: "https://api.com",
};
config.url = "https://new.com";
config.clientKey = "xyz789"; // 오류
3. 중첩 객체 (Nested Object)
객체 안의 객체도 타입으로 정의할 수 있다.
ts
type Payload = {
timestamp: string;
user: {
readonly id: string;
isActive?: boolean;
email: string[];
};
};
const payload: Payload = {
timestamp: "event",
user: {
id: "123",
isActive: true,
email: ["a@email.com", "b@email.com"],
},
};
- 주로 API 요청/응답 구조를 표현할 때 자주 사용한다.