모듈: 클래스

모듈: 클래스 (Module: Class)

클래스 하나를 통째로 내보내는 모듈을 다루다 보면, .d.ts 파일을 어떻게 구성해야 할지 막막할 때가 있어요. 이 템플릿은 클래스 하나를 내보내는 모듈의 타입 정의를 처음부터 잡아주는 출발점입니다. 실제로는 index.d.ts로 이름을 바꿔 모듈 이름과 같은 폴더에 넣어 쓰면 돼요.

출처: TypeScript 핸드북

언제 쓰는 템플릿인가요?

다음처럼 생긴 자바스크립트 코드와 함께 작업하고 싶을 때를 떠올려 보세요.

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

const greeter = new Greeter();
greeter.greet();

이 모듈은 new 키워드로 인스턴스를 만드는 클래스 생성자 함수 하나를 내보냅니다. 그래서 UMD를 통한 import와 일반 모듈 import를 모두 처리할 수 있도록 다음과 같은 템플릿을 쓰게 됩니다.

// Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
// Project: [~THE PROJECT NAME~]
// Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>

/*~ 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가 파일에서 내보내는 객체가 클래스 생성자 함수라는 사실을 선언하고, declare class 안에 그 클래스의 멤버들을 적어 넣는 구조죠. 클래스가 쓰는 타입(예를 들어 MyClassMethodOptions)은 declare namespace로 묶어서 함께 노출할 수 있어요. 이 namespace 형태를 쓰면 모듈이 namespace 객체로 잘못 import될 수 있으니, --esModuleInterop이 켜져 있지 않다면 import * as x from '...' 같은 형태는 피해야 합니다.

더 알아보기 (Learn more)