타입스크립트에서 네임스페이스의 활용

타입스크립트로 개발하면서 네임스페이스를 사용해보고 싶었다.

타입스크립트에서 네임스페이스의 활용

예제로 알아본다

// 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}.`;
    }
  }
}

위 예제를 보면 애니멀이라는 네임스페이스 안에 애니멀타입 인터페이스와 애니멀 클래스를 정의하고 있다. 애니멀 클래스는 애니멀타입 인터페이스를 인자로 받아 생성자에서 초기화 되고, 동물의 이름,, 나이 색상 , 소리등을 출력하는 각종 메소드를 구현한다.

이제 위의 예제 네임스페이스를 다른 파일에서 사용해보자

// app.ts 파일
import { Animal } from './animal';

const cat = new Animal.Animal({
  name: 'cat',
  age: 2,
  color: 'brown',
  sound: 'meow',
});

console.log(cat.getAnimalName());
console.log(cat.getAnimalAge());
console.log(cat.getAnimalColor());
console.log(cat.makeSound());

위 예제에서는 animal.ts파일에서 익스포트한 애니멀 네임스페이스를 임포트하여 Animal.Animal 클래스를 사용하고 있다. 클래스의 인스턴스를 생성하여 동물의 이름, 나이 색상, 소리등을 출력하는 각종 메소드를 호출한다.