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 =https://www.cnblogs.com/lxrNote/archive/2022/12/06/ [
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 = https://www.cnblogs.com/lxrNote/archive/2022/12/06/{ 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"
感謝觀看,歡迎互相討論與指導,以下是參考資料鏈接??
https://www.typescriptlang.org/static/TypeScript%20Types-ae199d69aeecf7d4a2704a528d0fd3f9.png
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/539374.html
標籤:其他
