Global-modifying Module .d.ts 템플릿

Global-modifying Module .d.ts 템플릿

전역 수정 모듈(global-modifying module) 은 import될 때 전역 스코프에 존재하는 값들을 변경하는 모듈이에요. 예를 들어 import되면 String.prototype에 새 멤버를 추가하는 라이브러리가 있을 수 있죠. 이 패턴은 런타임 충돌 가능성 때문에 다소 위험하지만, 그래도 선언 파일은 작성할 수 있어요.

출처: TypeScript 핸드북

전역 수정 모듈 식별하기

전역 수정 모듈은 보통 문서만 봐도 쉽게 식별할 수 있어요. 일반적으로 전역 플러그인과 비슷하지만, 효과를 발동시키려면 require 호출이 필요합니다.

이런 문서를 볼 수 있을 거예요.

// 'require' call that doesn't use its return value
var unused = require("magic-string-time");
/* or */
require("magic-string-time");

var x = "hello, world";
// Creates new methods on built-in types
console.log(x.startsWithHello());

var y = [1, 2, 3];
// Creates new methods on built-in types
console.log(y.reverseAndSort());

다음은 예시입니다.

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

/*~ This is the global-modifying module template file. 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: If your global-modifying module is callable or constructable, you'll
 *~ need to combine the patterns here with those in the module-class or module-function
 *~ template files
 */
declare global {
  /*~ Here, declare things that go in the global namespace, or augment
   *~ existing declarations in the global namespace
   */
  interface String {
    fancyFormat(opts: StringFormatOptions): string;
  }
}

/*~ If your module exports types or values, write them as usual */
export interface StringFormatOptions {
  fancinessLevel: number;
}

/*~ For example, declaring a method on the module (in addition to its global side effects) */
export function doSomething(): void;

/*~ If your module exports nothing, you'll need this line. Otherwise, delete it */
export {};

더 알아보기 (Learn more)