網站首頁 前端文檔 正文
前言:
回顧上一節的內容,在上一節中我們介紹了TS中最常見的聲明合并:接口合并
我們從中了解了聲明合并其實指的就是編譯器會針對同名的聲明合并為一個聲明,合并的結果是合并后的聲明會同時擁有原先兩個或多個聲明的特性
而接口合并的合并需要里面的成員是否有函數成員。對于里頭的函數成員來說,每個同名函數聲明都會被當成這個函數的一個重載,當接口 A與后來的接口 A合并時,后面的接口具有更高的優先級
今天要講的內容也是TS中的聲明合并,但這次是命名空間相關的合并
主要分兩方面來講,一是同名的命名空間之間的合并,二是命名空間和其他類型的合并。下面會一一講述
同名的命名空間之間的合并
與接口合并相類似,兩個或多個同名的命名空間也會合并其成員
那具體怎么合并呢?
對于同名的命名空間之間的合并,記住一下4點:
- 里頭模塊導出的同名接口會合并為一個接口
- 對于非導出成員,僅在其原有的(合并前的)命名空間內可見。也就是說合并之后,從其它命名空間合并進來的成員無法訪問非導出成員
- 對于里頭值的合并,如果里頭值的名字相同,那么后來的命名空間的值會優先級會更高
- 對于沒有沖突的成員,會直接混入
例如:
namespace Animals { export class Cat { } } namespace Animals { export interface Legged { numberOfLegs: number; } export class Dog { } }
等同于:
namespace Animals { export interface Legged { numberOfLegs: number; } export class Cat { } export class Dog { } }
上述例子中,兩個同名的命名空間Animals
,最終合并為一個命名空間,而且結果是三個沒有沖突的東西,直接混合在一起了
命名空間和其他類型的合并
命名空間可以與其它類型的聲明進行合并,比如與類和函數,比如和枚舉類型
合并同名的命名空間和類
例如:
class Album { label: Album.AlbumLabel; } namespace Album { export class AlbumLabel { }//導出 `AlbumLabel`類,好讓合并的類能訪問 }
命名空間和類的合并,結果是一個類并帶有一個內部類
合并同名的命名空間和函數
除了上述的內部類的模式,你在JavaScript
里,創建一個函數稍后擴展它增加一些屬性也是很常見的。 TypeScript
使用聲明合并來達到這個目的并保證類型安全
例如官方的一個例子:
function buildLabel(name: string): string { return buildLabel.prefix + name + buildLabel.suffix; } namespace buildLabel { export let suffix = ""; export let prefix = "Hello, "; } console.log(buildLabel("Sam Smith"));
同名的命名空間和枚舉
可以用來擴展枚舉,還是看官方給的例子吧
enum Color { red = 1, green = 2, blue = 4 } namespace Color { export function mixColor(colorName: string) { if (colorName == "yellow") { return Color.red + Color.green; } else if (colorName == "white") { return Color.red + Color.green + Color.blue; } else if (colorName == "magenta") { return Color.red + Color.blue; } else if (colorName == "cyan") { return Color.green + Color.blue; } } }
注意:
并不是所有東西都能合并,需要注意:類不能與其它類或變量合并
原文鏈接:https://juejin.cn/post/7035257522646679560
相關推薦
- 2022-07-27 python如何查找列表中元素的位置_python
- 2022-04-26 ASP.NET?Core?MVC中Required與BindRequired用法與區別介紹_基礎應用
- 2023-07-07 spring security權限路由匹配restful格式的詳情id設計
- 2022-06-25 pytorch中permute()函數用法補充說明(矩陣維度變化過程)_python
- 2022-05-12 databinding 與 RecyclerView.Adapter
- 2023-01-11 Python?基于xml.etree.ElementTree實現XML對比示例詳解_python
- 2022-03-19 .NET中的Husky工具及安裝方式_實用技巧
- 2022-05-13 C++ DeviceIoControl 獲取硬盤序列號
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支