TypeScript 인터페이스 | Interface 완벽 가이드
이 글의 핵심
TypeScript 인터페이스에 대한 실전 가이드입니다. Interface 완벽 가이드 등을 예제와 함께 상세히 설명합니다.
들어가며
Interface는 객체가 가져야 할 모양(shape)을 적은 규격입니다(인터페이스: 타입이 따라야 할 필드·메서드 약속을 적어 둔 것). 값마다 붙는 명찰을 “이 필드들은 꼭 있어야 한다” 수준으로 맞추는 도구라고 보시면 됩니다.
1. Interface 기본
선언
Interface는 객체가 가져야 할 프로퍼티와 타입을 정의합니다:
// User 인터페이스 선언
// 객체의 "계약(contract)"을 정의
interface User {
id: string; // 필수 프로퍼티: 문자열 타입의 id
name: string; // 필수 프로퍼티: 문자열 타입의 name
age: number; // 필수 프로퍼티: 숫자 타입의 age
email: string; // 필수 프로퍼티: 문자열 타입의 email
}
// ✅ 올바른 사용: 모든 프로퍼티 제공
const user: User = {
id: "U001",
name: "홍길동",
age: 25,
email: "[email protected]"
};
// TypeScript 컴파일러가 User 인터페이스와 비교하여 검증
// 모든 필수 프로퍼티가 있고 타입이 일치하므로 통과
// ❌ 컴파일 에러: 프로퍼티 누락
// const user2: User = {
// id: "U002",
// name: "김철수"
// // age와 email이 없음!
// };
// 에러 메시지:
// Type '{ id: string; name: string; }' is not assignable to type 'User'.
// Property 'age' is missing in type '{ id: string; name: string; }'
// ❌ 컴파일 에러: 타입 불일치
// const user3: User = {
// id: "U003",
// name: "이영희",
// age: "25", // string이지만 number 타입 필요
// email: "[email protected]"
// };
// 에러 메시지:
// Type 'string' is not assignable to type 'number'.
// ❌ 컴파일 에러: 추가 프로퍼티
// const user4: User = {
// id: "U004",
// name: "박민수",
// age: 30,
// email: "[email protected]",
// phone: "010-1234-5678" // User에 정의되지 않은 프로퍼티
// };
// 에러 메시지:
// Object literal may only specify known properties
Interface의 역할:
- 타입 체크: 컴파일 타임에 객체 구조 검증
- 자동 완성: IDE에서 프로퍼티 제안
- 문서화: 객체 구조를 명시적으로 표현
- 리팩토링: 타입 변경 시 모든 사용처 추적
선택적 프로퍼티
? 기호로 선택적 프로퍼티를 정의할 수 있습니다:
interface User {
id: string; // 필수 프로퍼티
name: string; // 필수 프로퍼티
age?: number; // 선택적 프로퍼티 (있어도 되고 없어도 됨)
email?: string; // 선택적 프로퍼티
}
// age?: number는 age: number | undefined와 동일
// ✅ OK: 선택적 프로퍼티 없이 생성
const user1: User = {
id: "U001",
name: "홍길동"
// age와 email이 없지만 선택적이므로 에러 없음
};
// ✅ OK: 선택적 프로퍼티 포함
const user2: User = {
id: "U002",
name: "김철수",
age: 30,
email: "[email protected]"
};
// 선택적 프로퍼티 사용 시 주의
function printAge(user: User) {
// user.age는 number | undefined 타입
// 직접 사용하면 에러 가능성
// ❌ 위험: age가 undefined일 수 있음
// console.log(user.age.toFixed(0)); // 런타임 에러 가능
// ✅ 안전: 타입 가드 사용
if (user.age !== undefined) {
// 이 블록 안에서 user.age는 number 타입으로 좁혀짐
console.log(user.age.toFixed(0));
}
// ✅ 안전: Optional Chaining
console.log(user.age?.toFixed(0)); // undefined면 undefined 반환
// ✅ 안전: 기본값 제공
const age = user.age ?? 0; // undefined면 0 사용
console.log(age);
}
printAge(user1); // age 없음
printAge(user2); // age 있음
선택적 프로퍼티의 장점:
- 유연한 객체 구조 정의
- 부분 업데이트 시 유용
- API 응답처럼 일부 필드가 없을 수 있는 경우
읽기 전용 프로퍼티
readonly 키워드로 변경 불가능한 프로퍼티를 정의할 수 있습니다:
interface User {
readonly id: string; // 읽기 전용: 초기화 후 변경 불가
name: string; // 일반 프로퍼티: 변경 가능
age: number;
}
// 객체 생성 시 초기화
const user: User = {
id: "U001", // 초기화 ✅
name: "홍길동",
age: 25
};
// 일반 프로퍼티는 변경 가능
user.name = "김철수"; // ✅ OK
user.age = 30; // ✅ OK
// readonly 프로퍼티는 변경 불가
// user.id = "U002"; // ❌ 컴파일 에러
// 에러 메시지:
// Cannot assign to 'id' because it is a read-only property.
// 실전 예시: 데이터베이스 엔티티
interface Post {
readonly id: string; // DB에서 자동 생성된 ID
readonly createdAt: Date; // 생성 시간 (변경 불가)
title: string; // 제목 (수정 가능)
content: string; // 내용 (수정 가능)
updatedAt: Date; // 수정 시간 (수정 가능)
}
const post: Post = {
id: "POST001",
createdAt: new Date(),
title: "첫 게시글",
content: "내용",
updatedAt: new Date()
};
// 게시글 수정
post.title = "수정된 제목"; // ✅ OK
post.content = "수정된 내용"; // ✅ OK
post.updatedAt = new Date(); // ✅ OK
// post.id = "POST002"; // ❌ 에러: ID는 변경 불가
// post.createdAt = new Date(); // ❌ 에러: 생성 시간 변경 불가
readonly vs const:
readonly: 프로퍼티에 사용 (객체의 속성)const: 변수에 사용 (변수 자체)
const user: User = { id: "U001", name: "홍길동", age: 25 };
// const: user 변수 자체를 재할당 불가
// user = { ... }; // ❌ 에러
// readonly: user.id 프로퍼티를 변경 불가
// user.id = "U002"; // ❌ 에러
2. 함수 타입
메서드
interface Calculator {
add(a: number, b: number): number;
subtract(a: number, b: number): number;
multiply?(a: number, b: number): number; // 선택적
}
const calc: Calculator = {
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
}
};
console.log(calc.add(10, 5));
console.log(calc.subtract(10, 5));
함수 타입
interface MathOperation {
(a: number, b: number): number;
}
const add: MathOperation = (a, b) => a + b;
const multiply: MathOperation = (a, b) => a * b;
console.log(add(10, 5));
console.log(multiply(10, 5));
생성자 타입
interface ClockConstructor {
new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
tick(): void;
}
class DigitalClock implements ClockInterface {
constructor(h: number, m: number) {}
tick() {
console.log("beep beep");
}
}
function createClock(
ctor: ClockConstructor,
hour: number,
minute: number
): ClockInterface {
return new ctor(hour, minute);
}
const clock = createClock(DigitalClock, 12, 17);
clock.tick();
3. 인덱스 시그니처
문자열 인덱스
interface StringMap {
[key: string]: string;
}
const colors: StringMap = {
red: "#FF0000",
green: "#00FF00",
blue: "#0000FF"
};
console.log(colors["red"]);
console.log(colors.green);
숫자 인덱스
interface NumberArray {
[index: number]: string;
}
const fruits: NumberArray = ["사과", "바나나", "오렌지"];
console.log(fruits[0]);
console.log(fruits[1]);
혼합 사용
interface Dictionary {
[key: string]: string | number;
length: number;
}
const dict: Dictionary = {
name: "홍길동",
age: 25,
length: 2
};
4. Interface 확장
extends
interface Person {
name: string;
age: number;
}
interface Employee extends Person {
employeeId: string;
department: string;
}
const employee: Employee = {
name: "홍길동",
age: 30,
employeeId: "E001",
department: "개발팀"
};
다중 확장
interface Timestamped {
createdAt: Date;
updatedAt: Date;
}
interface Identifiable {
id: string;
}
interface User extends Identifiable, Timestamped {
name: string;
email: string;
}
const user: User = {
id: "U001",
name: "홍길동",
email: "[email protected]",
createdAt: new Date(),
updatedAt: new Date()
};
5. Interface 병합
Declaration Merging
interface User {
name: string;
}
interface User {
age: number;
}
const user: User = {
name: "홍길동",
age: 25
};
라이브러리 확장
interface Window {
myCustomProperty: string;
}
window.myCustomProperty = "Hello!";
console.log(window.myCustomProperty);
6. 클래스와 Interface
implements
interface Animal {
name: string;
makeSound(): void;
}
class Dog implements Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound() {
console.log("멍멍!");
}
}
const dog = new Dog("바둑이");
dog.makeSound();
다중 구현
interface Flyable {
fly(): void;
}
interface Swimmable {
swim(): void;
}
class Duck implements Flyable, Swimmable {
fly() {
console.log("날아간다!");
}
swim() {
console.log("수영한다!");
}
}
const duck = new Duck();
duck.fly();
duck.swim();
7. Interface vs Type Alias
비교
| 특징 | Interface | Type Alias |
|---|---|---|
| 객체 타입 | ✅ | ✅ |
| Union/Intersection | ❌ | ✅ |
| 확장 | extends | & |
| 병합 | ✅ | ❌ |
| 원시 타입 | ❌ | ✅ |
예제
// Interface
interface User {
name: string;
}
interface User {
age: number;
}
// Type Alias
type Person = {
name: string;
};
// Type Alias는 Union 가능
type ID = string | number;
type Status = "active" | "inactive";
// Intersection
type Employee = Person & {
employeeId: string;
};
8. 실전 예제
예제 1: API 응답
interface ApiResponse<T> {
success: boolean;
data: T;
error?: string;
timestamp: Date;
}
interface User {
id: string;
name: string;
email: string;
}
async function fetchUser(id: string): Promise<ApiResponse<User>> {
try {
const response = await fetch(`/api/users/${id}`);
const data = await response.json();
return {
success: true,
data,
timestamp: new Date()
};
} catch (error) {
return {
success: false,
data: null as any,
error: "에러 발생",
timestamp: new Date()
};
}
}
예제 2: 폼 검증
interface FormField {
value: string;
error: string | null;
touched: boolean;
}
interface LoginForm {
email: FormField;
password: FormField;
}
const form: LoginForm = {
email: {
value: "",
error: null,
touched: false
},
password: {
value: "",
error: null,
touched: false
}
};
function validateEmail(email: string): string | null {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email) ? null : "올바른 이메일 형식이 아닙니다";
}
form.email.value = "[email protected]";
form.email.error = validateEmail(form.email.value);
form.email.touched = true;
예제 3: 이벤트 핸들러
interface ClickEvent {
x: number;
y: number;
button: "left" | "right";
}
interface EventHandler<T> {
(event: T): void;
}
const handleClick: EventHandler<ClickEvent> = (event) => {
console.log(`클릭: (${event.x}, ${event.y}), 버튼: ${event.button}`);
};
handleClick({ x: 100, y: 200, button: "left" });
정리
핵심 요약
- Interface: 객체 구조 정의
- 선택적 프로퍼티:
? - 읽기 전용:
readonly - 확장:
extends(다중 가능) - 구현:
implements(다중 가능) - 병합: Declaration Merging
Interface 사용 시기
- 객체 타입 정의
- 클래스 구조 강제
- 라이브러리 확장
- API 응답 타입
다음 단계
- TypeScript 제네릭
- TypeScript 유틸리티 타입
- TypeScript 데코레이터
관련 글
- TypeScript 고급 타입 | Union, Intersection, Literal 타입
- TypeScript 제네릭 | Generics 완벽 가이드
- C++ Adapter Pattern 완벽 가이드 | 인터페이스 변환과 호환성
- C++ numeric_limits |
- C++ 인터페이스 설계와 PIMPL: 컴파일 의존성을 끊고 바이너리 호환성(ABI) 유지하기 [#38-3]