主頁 > 企業開發 > TypeScript中的實用工具型別(Utility Types)

TypeScript中的實用工具型別(Utility Types)

2023-04-23 07:50:50 企業開發

TypeScript中的實用工具型別是一些預定義的泛型型別,可用于操作或創建其它新型別,這些實用工具型別在所有TypeScript專案中都是全域可用的,因此無需添加任務依賴項即可使用它們,

1.Partial<Type>

將Type的所有屬性都設定為可選的型別,

 1 interface Person {
 2   name: string;
 3    age: number;
 4   email: string;
 5 }
 6 
 7  type PartialPerson = Partial<Person>;
 8 
 9  //相當于
10  // interface Person {
11  //   name?: string | undefined;
12  //   age?: number | undefined;
13  //   email?: string | undefined;
14  // }
15 
16 interface Todo {
17    title: string;
18    description: string;
19 }
20 
21 function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
22    return { ...todo, ...fieldsToUpdate };
23 }
24 
25 const todo1 = {
26   title: "organize desk",
27   description: "clear clutter",
28 };
29 
30 const todo2 = updateTodo(todo1, {
31    description: "throw out trash",
32 });

2.Required<Type>

與Partical<Type> 相反,該型別由Type中所有屬性設定為required組成,

 1 interface Person {
 2  name?: string | undefined;
 3  age?: number | undefined;
 4  email?: string | undefined;
 5 }
 6 
 7 
 8 type RequiredPerson = Required<Person>;
 9 
10 // 相當于
11 // interface Person {
12 //   name: string;
13 //   age: number;
14 //   email: string;
15 // }

3.Omit<Type, Keys>

構建一個新型別--從型別 Type 中獲取所有屬性,然后從中剔除 Keys 屬性,

 1 interface User {
 2   id: number;
 3   name: string;
 4   email: string;
 5   age: number;
 6 }
 7 
 8 type UserWithoutEmail = Omit<User, 'email'>;
 9 
10 // 相當于
11 // interface Person {
12 //   id: string;
13 //   name: string;
14 //   age: number;
15 // }

也可以移除多個屬性,

 1 interface User {
 2   id: number;
 3   name: string;
 4   email: string;
 5   age: number;
 6 }
 7 
 8 type UserWithoutEmailAndName = Omit<User, 'email' | 'name'>;
 9 
10 // 相當于 
11 // interface Person {
12 //   id: string;
13 //   age: number;
14 // }

4.Pick<Type, Keys>

從型別 Type 中挑選部分屬性 Keys 來構造型別,與Omit相反,

 1 interface User {
 2   id: number;
 3   name: string;
 4   email: string;
 5   age: number;
 6 }
 7 
 8 type UserWithEmailAndName = Pick<User, 'email' | 'name'>;
 9 
10 // 相當于
11 // interface Person {
12 //   name: string;
13 //   email: string;
14 // }

可以組合使用這些型別,創造新的型別

 1 interface User {
 2   id: number;
 3   name: string;
 4   email: string;
 5   age: number;
 6 }
 7 
 8 type PartialPick = Partial<Pick<User, 'email' | 'name'>>;
 9 
10 // 相當于
11 // interface Person {
12 //   name?: string | undefined;
13 //   email?: string | undefined;
14 // }
 1 interface User {
 2   id: number;
 3   name: string;
 4   email: string;
 5   age: number;
 6 }
 7 
 8 type OmitPartialPick = Omit<Partial<Pick<User, 'email' | 'name'>>, 'email'>;
 9 
10 // 相當于 
11 // interface Person {
12 //   name?: string | undefined;
13 // }

5.Readonly<Type>

通過該Type構造新型別,并將它所有的屬性設定為只讀的,也就意味著構造出的型別的屬性不能被再次賦值,

 1 interface Person {
 2   id: number;
 3   name: string;
 4   age: number;
 5 }
 6 
 7 type ReadonlyPerson = Readonly<Person>;
 8 
 9 //相當于
10 // interface Person {
11 //   readonly id: number;
12 //   readonly name: string;
13 //   readonly age: number;
14 // }
15 
16 const person: ReadonlyPerson = {
17   id: 1,
18   name: 'John',
19   age: 25
20 };
21 
22 person.name = 'Mike'; // Error: Cannot assign to 'name' because it is a read-only property.

這個型別可用來表示在運行時會失敗的賦值運算式(比如,當嘗試給凍結物件的屬性再次賦值時)

Object.freeze

1 function freeze<T>(obj: T): Readonly<T>;

6.Record<Keys, Type>

構造一個物件型別,其屬性為Keys,屬性值為Type;該實用工具型別可用于將一種型別的屬性映射到另一種型別,

 1 interface CatInfo {
 2   age: number;
 3   breed: string;
 4 }
 5  
 6 type CatName = "miffy" | "boris" | "mordred";
 7  
 8 const cats: Record<CatName, CatInfo> = {
 9   miffy: { age: 10, breed: "Persian" },
10   boris: { age: 5, breed: "Maine Coon" },
11   mordred: { age: 16, breed: "British Shorthair" },
12 };
13  
14 cats.boris;
15  

7.Exclude<UnionType, ExcludedMembers>

通過從 UnionType 中排除所有可分配給 ExcludedMembers 的屬性來構造一個型別;也就是洗掉 union 型別的成員來創建新型別,

1 type T0 = Exclude<"a" | "b" | "c", "a">;
2 type T0 = "b" | "c"
3 
4 type T1 = Exclude<"a" | "b" | "c", "a" | "b">;
5 type T1 = "c"
6 
7 type T2 = Exclude<string | number | (() => void), Function>;
8 type T2 = string | number

8.Extract<Type, Union>

通過從 Type 中提取可分配給 Union 的所有聯合成員來構造一個型別,與 Exclude 相反,

1 type T0 = Extract<"a" | "b" | "c", "a" | "f">;
2 type T0 = "a"
3 
4 type T1 = Extract<string | number | (() => void), Function>;
5 type T1 = () => void

9.NonNullable<Type>

通過從 Type 中排除 null 和 undefined 來構造一個型別,

1 type T0 = NonNullable<string | number | undefined>;
2 type T0 = string | number
3 
4 type T1 = NonNullable<string[] | null | undefined>;
5 type T1 = string[]

10.ReturnType<Type>

由函式型別 Type 的回傳值型別構建一個新型別,

 1 function add(a: number, b: number): number {
 2   return a + b;
 3 }
 4 
 5 type AddReturnType = ReturnType<typeof add>;
 6 // type AddReturnType = number;
 7 
 8 
 9 function addStr(a: string, b: string): string{
10   return a + b;
11 }
12 
13 type AddReturnType2 = ReturnType<typeof addStr>;
14 // type AddReturnType2 = string;
15 
16 type T0 = ReturnType<() => string>;
17 type T0 = string
18 
19 type T1 = ReturnType<(s: string) => void>;
20 type T1 = void
21 
22 type T2 = ReturnType<<T>() => T>;    
23 type T2 = unknown
24 
25 type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
26 type T3 = number[]

11.Parameters<Type>

由函式型別 Type 的引數型別來構建出一個元組型別,

 1 function add(a: number, b: string, c:boolean): string {
 2   return a + b;
 3 }
 4 
 5 type AddReturnType = Parameters<typeof add>;
 6 // type AddReturnType = [a: number, b: string, c:boolean];
 7 
 8 type T0 = Parameters<() => string>;
 9 type T0 = []
10 
11 type T1 = Parameters<(s: string) => void>;
12 type T1 = [s: string]
13 
14 type T2 = Parameters<<T>(arg: T) => T>;
15 type T2 = [arg: unknown]

12.Awaited<Type>

這種型別旨在模擬異步函式中的 await 或 Promises 上的 .then() 方法等操作——具體來說,就是它們遞回展開 Promises 的方式,

 1 async function fetchData(): Promise<string> {
 2   // fetch data from API and return a string
 3 }
 4 
 5 type ResolvedResult = Awaited<ReturnType<typeof fetchData>>;
 6 // type ResolvedResult = string
 7 
 8 type A = Awaited<Promise<string>>;
 9 type A = string
10  
11 type B = Awaited<Promise<Promise<number>>>; 
12 type B = number
13  
14 type C = Awaited<boolean | Promise<number>>;  
15 type C = number | boolean

以上,是較常用的一些實用工具型別,

參考資料:

https://www.typescriptlang.org/docs/handbook/utility-types.html#uppercasestringtype

https://dev.to/arafat4693/typescript-utility-types-that-you-must-know-4m6k

 

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/550896.html

標籤:其他

上一篇:vue3組合式API介紹

下一篇:返回列表

標籤雲
其他(157887) Python(38092) JavaScript(25383) Java(17985) C(15215) 區塊鏈(8258) C#(7972) AI(7469) 爪哇(7425) MySQL(7137) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4557) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2430) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1959) Web開發(1951) HtmlCss(1921) python-3.x(1918) 弹簧靴(1913) C++(1910) xml(1889) PostgreSQL(1872) .NETCore(1854) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • IEEE1588PTP在數字化變電站時鐘同步方面的應用

    IEEE1588ptp在數字化變電站時鐘同步方面的應用 京準電子科技官微——ahjzsz 一、電力系統時間同步基本概況 隨著對IEC 61850標準研究的不斷深入,國內外學者提出基于IEC61850通信標準體系建設數字化變電站的發展思路。數字化變電站與常規變電站的顯著區別在于程序層傳統的電流/電壓互 ......

    uj5u.com 2020-09-10 03:51:52 more
  • HTTP request smuggling CL.TE

    CL.TE 簡介 前端通過Content-Length處理請求,通過反向代理或者負載均衡將請求轉發到后端,后端Transfer-Encoding優先級較高,以TE處理請求造成安全問題。 檢測 發送如下資料包 POST / HTTP/1.1 Host: ac391f7e1e9af821806e890 ......

    uj5u.com 2020-09-10 03:52:11 more
  • 網路滲透資料大全單——漏洞庫篇

    網路滲透資料大全單——漏洞庫篇漏洞庫 NVD ——美國國家漏洞庫 →http://nvd.nist.gov/。 CERT ——美國國家應急回應中心 →https://www.us-cert.gov/ OSVDB ——開源漏洞庫 →http://osvdb.org Bugtraq ——賽門鐵克 →ht ......

    uj5u.com 2020-09-10 03:52:15 more
  • 京準講述NTP時鐘服務器應用及原理

    京準講述NTP時鐘服務器應用及原理京準講述NTP時鐘服務器應用及原理 安徽京準電子科技官微——ahjzsz 北斗授時原理 授時是指接識訓通過某種方式獲得本地時間與北斗標準時間的鐘差,然后調整本地時鐘使時差控制在一定的精度范圍內。 衛星導航系統通常由三部分組成:導航授時衛星、地面檢測校正維護系統和用戶 ......

    uj5u.com 2020-09-10 03:52:25 more
  • 利用北斗衛星系統設計NTP網路時間服務器

    利用北斗衛星系統設計NTP網路時間服務器 利用北斗衛星系統設計NTP網路時間服務器 安徽京準電子科技官微——ahjzsz 概述 NTP網路時間服務器是一款支持NTP和SNTP網路時間同步協議,高精度、大容量、高品質的高科技時鐘產品。 NTP網路時間服務器設備采用冗余架構設計,高精度時鐘直接來源于北斗 ......

    uj5u.com 2020-09-10 03:52:35 more
  • 詳細解讀電力系統各種對時方式

    詳細解讀電力系統各種對時方式 詳細解讀電力系統各種對時方式 安徽京準電子科技官微——ahjzsz,更多資料請添加VX 衛星同步時鐘是我京準公司開發研制的應用衛星授時時技術的標準時間顯示和發送的裝置,該裝置以M國全球定位系統(GLOBAL POSITIONING SYSTEM,縮寫為GPS)或者我國北 ......

    uj5u.com 2020-09-10 03:52:45 more
  • 如何保證外包團隊接入企業內網安全

    不管企業規模的大小,只要企業想省錢,那么企業的某些服務就一定會采用外包的形式,然而看似美好又經濟的策略,其實也有不好的一面。下面我通過安全的角度來聊聊使用外包團的安全隱患問題。 先看看什么服務會使用外包的,最常見的就是話務/客服這種需要大量重復性、無技術性的服務,或者是一些銷售外包、特殊的職能外包等 ......

    uj5u.com 2020-09-10 03:52:57 more
  • PHP漏洞之【整型數字型SQL注入】

    0x01 什么是SQL注入 SQL是一種注入攻擊,通過前端帶入后端資料庫進行惡意的SQL陳述句查詢。 0x02 SQL整型注入原理 SQL注入一般發生在動態網站URL地址里,當然也會發生在其它地發,如登錄框等等也會存在注入,只要是和資料庫打交道的地方都有可能存在。 如這里http://192.168. ......

    uj5u.com 2020-09-10 03:55:40 more
  • [GXYCTF2019]禁止套娃

    git泄露獲取原始碼 使用GET傳參,引數為exp 經過三層過濾執行 第一層過濾偽協議,第二層過濾帶引數的函式,第三層過濾一些函式 preg_replace('/[a-z,_]+\((?R)?\)/', NULL, $_GET['exp'] (?R)參考當前正則運算式,相當于匹配函式里的引數 因此傳遞 ......

    uj5u.com 2020-09-10 03:56:07 more
  • 等保2.0實施流程

    流程 結論 ......

    uj5u.com 2020-09-10 03:56:16 more
最新发布
  • TypeScript中的實用工具型別(Utility Types)

    TypeScript中的實用工具型別是一些預定義的泛型型別,可用于操作或創建其它新型別。這些實用工具型別在所有TypeScript專案中都是全域可用的,因此無需添加任務依賴項即可使用它們。 1.Partial<Type> 將Type的所有屬性都設定為可選的型別。 1 interface Person ......

    uj5u.com 2023-04-23 07:50:50 more
  • vue3組合式API介紹

    為什么要使用Composition API? 根據官方的說法,vue3.0的變化包括性能上的改進、更小的 bundle 體積、對 TypeScript 更好的支持、用于處理大規模用例的全新 API,全新的api指的就是本文主要要說的組合式api。 在 vue3 版本之前,我們復用組件(或者提取和重用 ......

    uj5u.com 2023-04-23 07:50:45 more
  • 線上多域名實戰

    本文博主給大家分享線上多域名實戰,當線上主域名不可用的情況下,啟用備用域名完成網站高可用保障。 網站的高可用性一直是網站運維的重中之重。一旦網站宕機,不僅會造成巨大的經濟損失,也會嚴重影響用戶體驗。備份域名就是一種實作網站高可用的重要手段。通過備份域名,可以在主域名不可訪問時快速切換域名,保證網站正 ......

    uj5u.com 2023-04-23 07:50:00 more
  • Vue基礎知識

    模板語法 文本插值(text interpolation) 最基本的資料系結形式,使用“Mustache”語法即{{...}} <span>Message:{{msg}}</span> {{}}中的值會被替換為相應組件實體中msg屬性的值,且會同步地更新 原始HTML <p>Message:<spa ......

    uj5u.com 2023-04-23 07:49:54 more
  • react18中antd的Upload組件上傳頭像,并且拿到服務器回傳的頭像的u

    業務需求:上傳頭像,上傳完畢后拿到頭像的url,把頭像展示在頁面中,最終把頭像url和其他用戶資訊一起發送給服務器 上傳頭像流程 匯入 Upload 組件和圖示(一個加號,一個加載中) import { Upload } from 'antd'; import { PlusOutlined, Loa ......

    uj5u.com 2023-04-23 07:49:45 more
  • 博客園頁面展示--前端及樣式代碼

    這是一個博客園的首頁面的展示前端代碼和樣式代碼 樣式代碼CSS采用外部鏈接,建好檔案直接復制運行vscode即可,話不多說,直接上代碼 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Mickey - 博客園</title> < ......

    uj5u.com 2023-04-23 07:49:36 more
  • 仿chatGPT或chatPDF的前端界面布局,css實作對話聊天布局代碼,回應

    chatPDF或者chatGPT的界面挺簡潔的,就是一個左側的串列以及右側的對話串列,現在使用css實作這樣的布局 充分運用了flex布局方式實作,左右分欄,以及對話形式展示效果 下面是效果圖: 在手機設備看就隱藏左側,右側100%適應 下面就是html和css的布局代碼 <style> .chat ......

    uj5u.com 2023-04-23 07:49:27 more
  • TypeScript中的實用工具型別(Utility Types)

    TypeScript中的實用工具型別是一些預定義的泛型型別,可用于操作或創建其它新型別。這些實用工具型別在所有TypeScript專案中都是全域可用的,因此無需添加任務依賴項即可使用它們。 1.Partial<Type> 將Type的所有屬性都設定為可選的型別。 1 interface Person ......

    uj5u.com 2023-04-23 07:49:13 more
  • 線上多域名實戰

    本文博主給大家分享線上多域名實戰,當線上主域名不可用的情況下,啟用備用域名完成網站高可用保障。 網站的高可用性一直是網站運維的重中之重。一旦網站宕機,不僅會造成巨大的經濟損失,也會嚴重影響用戶體驗。備份域名就是一種實作網站高可用的重要手段。通過備份域名,可以在主域名不可訪問時快速切換域名,保證網站正 ......

    uj5u.com 2023-04-23 07:48:23 more
  • 博客園頁面展示--前端及樣式代碼

    這是一個博客園的首頁面的展示前端代碼和樣式代碼 樣式代碼CSS采用外部鏈接,建好檔案直接復制運行vscode即可,話不多說,直接上代碼 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Mickey - 博客園</title> < ......

    uj5u.com 2023-04-23 07:48:00 more