Type 描述:全稱叫做 '類型別名',為類型字面量提供名稱。比 Interface 支持更豐富的類型系統特性。 Type 與 Interface 區別 Interface 只能描述對象的形狀,Type 不止 Interface 能多次聲明進行擴展,Type 不行 在性能方面,Type 介面檢查能夠 ...
Type
描述:全稱叫做 '類型別名',為類型字面量提供名稱。比 Interface 支持更豐富的類型系統特性。
Type 與 Interface 區別
- Interface 只能描述對象的形狀,Type 不止
- Interface 能多次聲明進行擴展,Type 不行
- 在性能方面,Type 介面檢查能夠更快
特性
和變數類似,可以在不同的作用域中創建具有相同的名稱。
TypeScript 內置了許多全局類型,將幫助你在類型系統完成常用的任務。
對象字面量語法( Object Literal Syntax )
type JsonRsponse = { version: number; outOfStock?: boolean; // 可選屬性 readonly body: string; // 只讀屬性 /** In bytes */ payloadSize: number; // 編輯器註釋提示 update: (retryTimes: number) => void; // 箭頭函數方法 update2(retryTimes: number): void; // 方法 (): JsonRsponse; // 函數 [key: string]: number; // 接受字元串索引,值為number new (s: string): JSONResponse; // 構造函數 }
這些對象字面量的語法和 Interface 的沒有區別,詳情可閱讀我另一篇 Interface 隨筆。https://www.cnblogs.com/lxrNote/p/16953606.html
原始類型( Primitive Type )
type SanitizedIput = string
type MissingNo = 404
元組類型(Tuple Type)
元組是知道明確下標的特殊數組type Data = [
location: Location,
timestamp: string
]
聯合類型(Union Type)
聯合類型是描述眾多類型之一type Size = "small" | "medium" | "large"
交叉類型(Intersection Types)
一種擴展/合併的方法type local = { x: number } & { y: number } // local {x:number;y:number}
索引類型(Type Indexing)
如果其它類型別名是引用類型,可以通過索引獲取其值類型
type Res = { data: { x: string } } type Content = Res["data"] // Conent {x:string}
類型來自值(Type from Value)
重用通過 typeof 運算符取出值在JavaScript 運行時的類型const data = { x: 123 } type Content2 = typeof data // Content2 = { x: number }
類型來自方法返回值(Type from Func Return)
重用方法的返回值作為類型,ReturnType 是內置全局類型const createFixtures = ()=>{ return 123} type Fixtures = ReturnType<typeof createFixtures> // Fixtures = numer
類型來自模塊(Type from Module)
const data: import("./data").data
沒看懂,知道的朋友指導下。。。。。。
映射類型(Mapped Types)
type Artist = {name: string,bio: string} type Subscriber<Type> = { // 迴圈遍歷泛型參數 Type 的每一個欄位 [Property in keyof Type]: (nv: Type[Property]) => void //設置類型為一個函數,原始類型為參數 } type ArtisSub = Subscriber<Artist> // { name: (nv: string)=>void, bio: (nv:string)=>void }
條件類型(Conditional Types)
在類型系統中充當 if 語句,通過泛型創建,通常用於減少聯合類型中的選項數量。type HasFourLegs<Animal> = Animal extends { legs: 4 } ? Animal : never type Bird = { cry: '唧唧喳喳', legs: 2 } type Dog = { cry: '汪汪汪', legs: 4 } type Ant = { cry: '...', legs: 6 } type Wolf = { cry: '嗷嗚~', legs: 4 } type Animal = Bird | Dog | Ant | Wolf type FourLegs = HasFourLegs<Animal> // FourLegs = Dog | Wolf
模板聯合類型(Template Union Types)
字元串模板可以用來組合和操縱類型系統中的文本type SupportedLangs = "en" | "pt" | "zh"; type FooterLocaleIDs = "header" | "footer"; type AllLocaleIDs = `${SupportedLangs}_${FooterLocaleIDs}_id`; // "en_header_id" | "en_footer_id" | "pt_header_id" | "pt_footer_id" | "zh_header_id" | "zh_footer_id"
感謝觀看,歡迎互相討論與指導,以下是參考資料鏈接