全域 .d.ts

全域函式庫

全域函式庫是可以從全域範圍存取的函式庫(也就是說,不需要使用任何形式的 import)。許多函式庫只會公開一個或多個全域變數供使用。例如,如果你使用 jQuery,只要參照 $ 變數就可以使用它

ts
$(() => {
console.log("hello!");
});

你通常會在全域函式庫的說明文件中看到如何使用 HTML 腳本標籤中的函式庫

html
<script src="http://a.great.cdn.for/someLib.js"></script>

目前,大多數熱門的全域存取函式庫實際上都是以 UMD 函式庫撰寫的(請參閱下方)。UMD 函式庫的說明文件很難與全域函式庫的說明文件區分。在撰寫全域宣告檔案之前,請確定函式庫不是 UMD。

js
function createGreeting(s) {
return "Hello, " + s;
}

或如下所示

js
window.createGreeting = function (s) {
return "Hello, " + s;
};

在檢視全域函式庫的程式碼時,您通常會看到

  • 頂層的 var 陳述式或 function 宣告
  • 一個或多個指定給 window.someName
  • 假設 DOM 原生函式,例如 documentwindow 存在

不會看到

  • 檢查或使用模組載入器,例如 requiredefine
  • CommonJS/Node.js 型式的匯入,例如 var fs = require("fs");
  • 呼叫 define(...)
  • 說明如何 require 或匯入函式庫的文件

全域函式庫範例

由於通常很容易將全域函式庫轉換為 UMD 函式庫,因此很少有熱門函式庫仍以全域樣式撰寫。不過,小型且需要 DOM(或沒有相依項目的)函式庫可能仍然是全域的。

全域函式庫範本

您可以在下方看到 DTS 範例

ts
// Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
// Project: [~THE PROJECT NAME~]
// Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>
/*~ If this library is callable (e.g. can be invoked as myLib(3)),
*~ include those call signatures here.
*~ Otherwise, delete this section.
*/
declare function myLib(a: string): string;
declare function myLib(a: number): number;
/*~ If you want the name of this library to be a valid type name,
*~ you can do so here.
*~
*~ For example, this allows us to write 'var x: myLib';
*~ Be sure this actually makes sense! If it doesn't, just
*~ delete this declaration and add types inside the namespace below.
*/
interface myLib {
name: string;
length: number;
extras?: string[];
}
/*~ If your library has properties exposed on a global variable,
*~ place them here.
*~ You should also place types (interfaces and type alias) here.
*/
declare namespace myLib {
//~ We can write 'myLib.timeout = 50;'
let timeout: number;
//~ We can access 'myLib.version', but not change it
const version: string;
//~ There's some class we can create via 'let c = new myLib.Cat(42)'
//~ Or reference e.g. 'function f(c: myLib.Cat) { ... }
class Cat {
constructor(n: number);
//~ We can read 'c.age' from a 'Cat' instance
readonly age: number;
//~ We can invoke 'c.purr()' from a 'Cat' instance
purr(): void;
}
//~ We can declare a variable as
//~ 'var s: myLib.CatSettings = { weight: 5, name: "Maru" };'
interface CatSettings {
weight: number;
name: string;
tailLength?: number;
}
//~ We can write 'const v: myLib.VetID = 42;'
//~ or 'const v: myLib.VetID = "bob";'
type VetID = string | number;
//~ We can invoke 'myLib.checkCat(c)' or 'myLib.checkCat(c, v);'
function checkCat(c: Cat, s?: VetID);
}

TypeScript 文件是一個開源專案。歡迎透過 傳送 Pull Request ❤ 來協助我們改善這些頁面

此頁面的貢獻者
MHMohamed Hegazy (53)
OTOrta Therox (13)
1+

最後更新時間:2024 年 3 月 21 日