모듈: 클래스(Module: Class)

모듈: 클래스(Module: Class)

클래스 하나만 export 하는 모듈의 타입 정의를 만들 때 쓰는 템플릿이에요. new로 인스턴스를 만들어 쓰는 형태의 라이브러리(예: Greeter)를 CommonJS 스타일과 UMD 두 방식 모두에서 import 할 수 있게 잡아주는 방법을 보여드릴게요.

출처: TypeScript 공식문서

본문

예를 들어, 아래처럼 생긴 JavaScript 코드를 다뤄야 한다고 생각해볼게요.

const Greeter = require("super-greeter");

const greeter = new Greeter();

greeter.greet();

UMD로 import 하는 방식과 모듈로 import 하는 방식을 둘 다 지원하려면, index.d.ts 파일을 이렇게 만들어 주시면 돼요.

// Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
// Project: [~THE PROJECT NAME~]
// Definitions by: [~YOUR NAME~]

/*~ This is the module template file for class modules.

 *~ You should rename it to index.d.ts and place it in a folder with the same name as the module.

 *~ For example, if you were writing a file for "super-greeter", this

 *~ file should be 'super-greeter/index.d.ts'

 */

// Note that ES6 modules cannot directly export class objects.

// This file should be imported using the CommonJS-style:

//   import x = require('[~THE MODULE~]');

//

// Alternatively, if --allowSyntheticDefaultImports or

// --esModuleInterop is turned on, this file can also be

// imported as a default import:

//   import x from '[~THE MODULE~]';

//

// Refer to the TypeScript documentation at

// https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require

// to understand common workarounds for this limitation of ES6 modules.

/*~ If this module is a UMD module that exposes a global variable 'myClassLib' when

 *~ loaded outside a module loader environment, declare that global here.

 *~ Otherwise, delete this declaration.

 */

export as namespace myClassLib;

/*~ This declaration specifies that the class constructor function

 *~ is the exported object from the file

 */

export = Greeter;

/*~ Write your module's methods and properties in this class */

declare class Greeter {

  constructor(customGreeting?: string);

  greet: void;

  myMethod(opts: MyClass.MyClassMethodOptions): number;

}

/*~ If you want to expose types from your module as well, you can

 *~ place them in this block.

 *~

 *~ Note that if you decide to include this namespace, the module can be

 *~ incorrectly imported as a namespace object, unless

 *~ --esModuleInterop is turned on:

 *~   import * as x from '[~THE MODULE~]'; // WRONG! DO NOT DO THIS!

 */

declare namespace MyClass {

  export interface MyClassMethodOptions {

    width?: number;

    height?: number;

  }

}

이 템플릿의 핵심 포인트를 옆에서 짚어드리자면 이래요.

  • export = Greeter; 한 줄이 이 파일의 전부라고 해도 과언이 아니에요. 클래스 생성자 함수 자체를 모듈 바깥으로 내보내겠다는 뜻이라, 사용하는 쪽은 new Greeter()로 인스턴스를 만들 수 있는 거예요. 클래스 모듈이니까 export 대상이 "클래스 생성자"라는 걸 꼭 기억해두세요.
  • ES6 모듈 문법(export default class)으로는 클래스 객체를 바로 내보낼 수 없기 때문에, CommonJS 스타일인 import x = require('[~THE MODULE~]')로 불러오는 걸 기본값으로 잡아요. 다만 --allowSyntheticDefaultImports--esModuleInterop을 켜면 import x from '[~THE MODULE~]'처럼 기본 import도 가능해져요.
  • UMD 모듈이라면 export as namespace myClassLib;로 전역 변수 이름을 선언해줘요. 모듈 로더 환경 밖에서 전역으로 쓰일 일이 없다면 이 줄은 그냥 지우면 됩니다.
  • declare namespace MyClass 블록은 타입을 추가로 노출하고 싶을 때 쓰는 공간이에요. 다만 여기 있는 타입을 쓰려면 MyClass.MyClassMethodOptions처럼 네임스페이스 경로로 접근해야 하니까, --esModuleInterop이 꺼져 있으면 실수로 import * as x from ...처럼 잘못된 방식으로 불러올 수 있어요. 주석에도 // WRONG! DO NOT DO THIS!라고 경고가 달려 있죠.

즉, 클래스 하나만 내보내는 모듈의 타입 정의는 export =로 클래스를 내보내고, 부가적인 타입이 있으면 네임스페이스 안에 정리해두는 구조로 잡아주시면 됩니다.

더 알아보기