3분 읽기
Last updated on
타입스크립트에서 네임스페이스의 활용
📦 네임스페이스란?
TypeScript의 네임스페이스는 코드를 논리적으로 그룹화하여 전역 네임스페이스 오염을 방지하는 방법입니다. 관련된 인터페이스, 클래스, 함수 등을 하나의 이름 아래 묶어서 관리할 수 있습니다.
🎯 네임스페이스 정의하기
예제로 알아보겠습니다.
animal.ts 파일
// animal.ts 파일
export namespace Animal {
export interface AnimalType {
name: string;
age: number;
color: string;
sound: string;
}
export class Animal {
constructor(public animal: AnimalType) {}
getAnimalName() {
return `This animal's name is ${this.animal.name}.`;
}
getAnimalAge() {
return `This animal is ${this.animal.age} years old.`;
}
getAnimalColor() {
return `This animal's color is ${this.animal.color}.`;
}
makeSound() {
return `The ${this.animal.name} makes the sound ${this.animal.sound}.`;
}
}
}
위 예제를 보면 Animal
이라는 네임스페이스 안에:
AnimalType
인터페이스를 정의Animal
클래스를 정의
Animal
클래스는 AnimalType
인터페이스를 인자로 받아 생성자에서 초기화되고, 동물의 이름, 나이, 색상, 소리 등을 출력하는 각종 메소드를 구현합니다.
🔧 네임스페이스 사용하기
이제 위의 예제 네임스페이스를 다른 파일에서 사용해보겠습니다.
app.ts 파일
// app.ts 파일
import { Animal } from './animal';
const cat = new Animal.Animal({
name: 'cat',
age: 2,
color: 'brown',
sound: 'meow',
});
console.log(cat.getAnimalName()); // This animal's name is cat.
console.log(cat.getAnimalAge()); // This animal is 2 years old.
console.log(cat.getAnimalColor()); // This animal's color is brown.
console.log(cat.makeSound()); // The cat makes the sound meow.
위 예제에서는 animal.ts
파일에서 export한 Animal
네임스페이스를 import하여 Animal.Animal
클래스를 사용하고 있습니다. 클래스의 인스턴스를 생성하여 동물의 정보를 출력하는 각종 메소드를 호출합니다.
💡 네임스페이스 vs 모듈
네임스페이스 사용이 적합한 경우
- 전역 스코프에서 코드를 구조화할 때
- 레거시 코드와의 호환성이 필요할 때
- 단일 파일로 배포되는 라이브러리를 만들 때
모듈 사용이 적합한 경우 (권장)
- 현대적인 모듈 시스템을 사용할 때
- 코드 분할과 트리 쉐이킹이 필요할 때
- npm 패키지로 배포할 때
🎨 더 나은 대안: ES6 모듈
현대적인 TypeScript 프로젝트에서는 네임스페이스보다 ES6 모듈을 사용하는 것이 권장됩니다:
// animal.ts (모듈 방식)
export interface AnimalType {
name: string;
age: number;
color: string;
sound: string;
}
export class Animal {
constructor(public animal: AnimalType) {}
getAnimalName() {
return `This animal's name is ${this.animal.name}.`;
}
// ... 나머지 메소드
}
// app.ts
import { Animal, AnimalType } from './animal';
const cat = new Animal({
name: 'cat',
age: 2,
color: 'brown',
sound: 'meow',
});
📝 결론
네임스페이스는 TypeScript의 유용한 기능이지만, 현재는 ES6 모듈이 더 선호됩니다. 레거시 코드나 특별한 요구사항이 있는 경우가 아니라면 ES6 모듈 시스템을 사용하는 것을 권장합니다.