TypeScript 學習筆記 之 Module

2021-08-29 07:27:30 字數 1789 閱讀 3248

ts 中的 module 的概念相容 es 2015 中 module 的概念。

模組中的**屬於模組本身的作用域,而不是全域性作用域。也這就意味著沒有明確的export的話,模組中的 變數,函式,類等對其他模組是不見的。相對的其他模組要使用某一模組的內容需要通過import匯入。

匯出語句:也可以像import語句的逆形式一樣,通過類似如下的語句匯出:

export ;

export ;

從其他模組中匯出:export from "./users" }

從其他模組中匯出全部:export * from ".users"

從模組中匯入單個匯出:import from "./users"匯出時重新命名 :import from "./users"從模組中匯入全部到乙個變數名中:import * as users from "./users"單純的匯入模組以執行模組:import "./my-module.js"每乙個模組都有乙個可選的預設匯出. 在export後面加default關鍵字。

default匯出也支援匯出字面量。如:export default "123";

在 commonjs 和 amd 模組系統中都乙個exports的變數,用來包裝乙個模組的所有匯出。為了相容這些模組系統。 ts 也支援export =的語法來匯出模組的單個物件。但是注意export =必須和import module = require("module")搭配使用。

在 ts 的術語中把沒有定義實現的宣告稱之為ambient。這些宣告一般定義在.d.ts檔案中。你可以把他們理解成c/c++中的標頭檔案。

例如有乙個名為node.d.ts的檔案。

然後便可以將下面一樣來匯入:

/// import * as url from "url";

let myurl = url.parse("");

ts 也提供了不提供模組的具體的宣告文,來匯入 js 庫的支援。

即提供一種簡寫的方式:

如下declarations.d.ts

declare module "hot-new-module";
這樣模組中所有的匯入的型別都將是any型別。

import x, from "hot-new-module";

匯出層級不要太深。從模組中匯出乙個 namespace 加增加乙個層級。如果沒有必要不要增加層級 。

如果只匯出乙個單一的類或函式,使用export default

匯出多個物件時,把他們放在最頂層。

顯式的列出所有要匯入的名字。

如果要匯入很多的東西的時候,可以考慮使用 namespace 匯入模式。

import * as largemodule from "./mylargemodule.ts";

通過 re-export 來擴充套件。

不要在模組中使用 namespaces。

Typescript學習筆記

物件導向特性 類類的宣告 用class關鍵字 加類名 class person 類宣告完之後就可以被例項化了,類相當於乙個模子.name string eat var p1 new person p1.name batman p1.eat var p2 new person p2.name supe...

typescript學習筆記

1,ts是js的超集,ts是強型別語言。ts比js入門更難。ts的物件導向寫法比js更優雅。ts更適合團隊協作。2,宣告變數篇。3,宣告函式篇。4,物件導向篇。4.1,子類繼承父類 extends 繼承多個介面 implements。4.2,this表示當前物件,super表示父類物件。子類不寫co...

TypeScript 學習筆記1

inte ces typescript 的 type checking 專注於值的 shape inte ces的作用在於命名值使其便於檢測,同時作為軟體與軟體 軟體內部交流的工具。用於檢測,編譯成js的話沒有相應的語句 ts inte ce squareconfig function creats...