例如,當您要使用延伸其他函式庫的 JavaScript 程式碼時。
ts
import { greeter } from "super-greeter";// Normal Greeter APIgreeter(2);greeter("Hello world");// Now we extend the object with a new function at runtimeimport "hyper-super-greeter";greeter.hyperGreet();
「super-greeter」的定義
ts
/*~ This example shows how to have multiple overloads for your function */export interface GreeterFunction {(name: string): void(time: number): void}/*~ This example shows how to export a function specified by an interface */export const greeter: GreeterFunction;
我們可以像以下這樣延伸現有模組
ts
// 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 plugin 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'*//*~ On this line, import the module which this module adds to */import { greeter } from "super-greeter";/*~ Here, declare the same module as the one you imported above*~ then we expand the existing declaration of the greeter function*/export module "super-greeter" {export interface GreeterFunction {/** Greets even better! */hyperGreet(): void;}}
這使用 宣告合併
ES6 對模組外掛的影響
有些外掛會新增或修改現有模組的頂層匯出。雖然這在 CommonJS 和其他載入器中是合法的,但 ES6 模組被視為不可變的,因此這種模式將無法使用。由於 TypeScript 與載入器無關,因此不會在編譯時強制執行這項政策,但打算轉換到 ES6 模組載入器的開發人員應注意這一點。