TypeScript 中的型別系統是非常強大的。它為我們提供了型別安全。型別系統雖然受人喜愛,但如果我們不規劃和設計型別和介面,它也會讓我們的程式碼變得混亂難讀。
避免程式碼重複中,建立可重用的型別,是我們編寫簡潔程式碼重要的一環。泛型是 TypeScript 的一個功能,它允許我們編寫可重用的型別。看下面的例子:
type Add<T> = (a: T, b: T) => T const addNumbers: Add<number> = (a, b) => { return a + b } const addStrings: Add<string> = (a, b) => { return a + b }
將正確的型別放入Add
的泛型中,它可以被用來描述兩個數位的相加或兩個字串的連線。我們不需要為每個函數寫一個型別,而只需要用泛型做一次。這不僅節省了我們的精力,而且還使我們的程式碼更加簡潔,更不容易出錯。
TypeScript 原生提供了幾個有用的實用型別來幫助我們進行一些常見的型別轉換。這些實用型別是全域性可用的,它們都使用了泛型。
下面這7個是我經常用到的。
1. Pick<Type, Keys>
Pick
會從 Type 中挑選屬性集 Keys 來建立一個新的型別,Keys 可以是一個字串字面或字串字面的聯合。Keys 的值必須是 Type 的鍵,否則TypeScript編譯器會抱怨。當你想通過從有很多屬性的物件中挑選某些屬性來建立更輕的物件時,這個實用型別特別有用。
type User = { name: string age: number address: string occupation: string } type BasicUser = Pick<User, "name" | "age"> // type BasicUser = { // name: string; // age: number; // }
2. Omit<Type, Keys>
Omit
與Pick
相反。 Keys
不是說要保留哪些屬性,而是指要省略的屬性鍵集。 當我們只想從物件中刪除某些屬性並保留其他屬性時,這個會更有用。
type User = { name: string age: number address: string occupation: string } type BasicUser = Omit<User, "address" | "occupation"> // type BasicUser = { // name: string; // age: number; // }
3. Partial<Type>
Partial
構造了一個型別,其所有的型別屬性都設定為可選。當我們在編寫一個物件的更新邏輯時,這個可能非常有用。
type User = { name: string age: number address: string occupation: string } type PartialUser = Partial<User> // type PartialUser = { // name?: string; // age?: number; // address?: string; // occupation?: string; // }
4. Required<Type>
Required
與Partial
相反。它構造了一個型別的所有屬性都是必填的型別。它可以被用來確保在一個型別中沒有可選屬性出現。
type PartialUser = { name: string age: number address?: string occupation?: string } type User = Required<PartialUser> // type User = { // name: string; // age: number; // address: string; // occupation: string; // }
5. Readonly<Type>
Readonly
構建了一個型別,其型別的所有屬性被設定為唯讀。重新分配新的值 TS 就會報錯。
type User = { name: string age: number address: string occupation: string } type ReadOnlyUser = Readonly<User> const user: ReadOnlyUser = { name: "小智", age: 24, address: "廈門", occupation: "大遷世界" } user.name = "王大冶" // Cannot assign to 'name' because it is a read-only property.
6. ReturnType<Type>
ReturnType
從一個函數型別的返回型別構建一個型別。當我們處理來自外部庫的函數型別並希望基於它們建立自定義型別時,它是非常有用的。
import axios from 'axios' type Response = ReturnType<typeof axios> function callAPI(): Response{ return axios("url") }
除了上面提到的,還有其他實用型別可以幫助我們編寫更乾淨程式碼。關於實用工具型別的TypeScript檔案連結可以在這裡找到。
https://www.typescriptlang.org/docs/handbook/utility-types.html
實用型別是TypeScript提供的非常有用的功能。開發人員應該利用它們來避免寫死型別。要比同事更秀? 這些就是你需要知道的!
本文轉載在:https://segmentfault.com/a/1190000040574488
更多程式設計相關知識,請存取:!!
以上就是淺談TypeScript中值得了解的7個方法的詳細內容,更多請關注TW511.COM其它相關文章!