成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

TypeScript 高級類型入門手冊:附大量代碼實例

開發 前端
TypeScript 是一種類型化的語言,允許你指定變量的類型,函數參數,返回的值和對象屬性。你可以把本文看做一個帶有示例的 TypeScript 高級類型備忘單,讓我們開始吧!

[[419185]]

 TypeScript 是一種類型化的語言,允許你指定變量的類型,函數參數,返回的值和對象屬性。

你可以把本文看做一個帶有示例的 TypeScript 高級類型備忘單

讓我們開始吧!

Intersection Types(交叉類型)

交叉類型是一種將多種類型組合為一種類型的方法。這意味著你可以將給定的類型 A 與類型 B 或更多類型合并,并獲得具有所有屬性的單個類型。 

  1. type LeftType = {  
  2.     id: number;  
  3.     left: string;  
  4. };  
  5. type RightType = {  
  6.     id: number;  
  7.     right: string;  
  8. };  
  9. type IntersectionType = LeftType & RightType;  
  10. function showType(args: IntersectionType) {  
  11.     console.log(args);  
  12.  
  13. showType({ id: 1, left: 'test', right: 'test' });  
  14. // Output: {id: 1, left: "test", right: "test"} 

如你所見,IntersectionType組合了兩種類型-LeftType和RightType,并使用&符號形成了交叉類型。

Union Types(聯合類型)

聯合類型使你可以賦予同一個變量不同的類型 

  1. type UnionType = string | number;  
  2. function showType(arg: UnionType) {  
  3.     console.log(arg); 
  4.  
  5. showType('test');  
  6. // Output: test  
  7. showType(7);  
  8. // Output: 7 

函數showType是一個聯合類型函數,它接受字符串或者數字作為參數。

Generic Types(泛型)

泛型類型是復用給定類型的一部分的一種方式。它有助于捕獲作為參數傳遞的類型 T。

優點: 創建可重用的函數,一個函數可以支持多種類型的數據。這樣開發者就可以根據自己的數據類型來使用函數

泛型函數 

  1. function showType<T>(args: T) {  
  2.     console.log(args);  
  3.  
  4. showType('test'); 
  5. // Output: "test"  
  6. showType(1);  
  7. // Output: 1 

如何創建泛型類型:需要使用<>并將 T(名稱可自定義)作為參數傳遞。上面的 🌰 栗子中, 我們給 showType 添加了類型變量 T。T幫助我們捕獲用戶傳入的參數的類型(比如:number/string)之后我們就可以使用這個類型

我們把 showType 函數叫做泛型函數,因為它可以適用于多個類型

泛型接口 

  1. interface GenericType<T> {  
  2.     id: number;  
  3.     name: T;  
  4.  
  5. function showType(args: GenericType<string>) {  
  6.     console.log(args);  
  7.  
  8. showType({ id: 1, name: 'test' });  
  9. // Output: {id: 1, name: "test"}  
  10. function showTypeTwo(args: GenericType<number>) {  
  11.     console.log(args);  
  12.  
  13. showTypeTwo({ id: 1, name: 4 });  
  14. // Output: {id: 1, name: 4} 

在上面的栗子中,聲明了一個 GenericType 接口,該接口接收泛型類型 T, 并通過類型 T來約束接口內 name 的類型

注:泛型變量約束了整個接口后,在實現的時候,必須指定一個類型

因此在使用時我們可以將name設置為任意類型的值,示例中為字符串或數字

多參數的泛型類型 

  1. interface GenericType<T, U> {  
  2.     id: T;  
  3.     name: U;  
  4.  
  5. function showType(args: GenericType<number, string>) { 
  6.     console.log(args); 
  7.  
  8. showType({ id: 1, name: 'test' });  
  9. // Output: {id: 1, name: "test"}   
  10. function showTypeTwo(args: GenericType<string, string[]>) {  
  11.     console.log(args);  
  12.  
  13. showTypeTwo({ id: '001', name: ['This', 'is', 'a', 'Test'] });  
  14. // Output: {id: "001", name: Array["This", "is", "a", "Test"]} 

泛型類型可以接收多個參數。在上面的代碼中,我們傳入兩個參數:T和U,然后將它們用作id,name的類型。也就是說,我們現在可以使用該接口并提供不同的類型作為參數。

Utility Types

TypeScript 內部也提供了很多方便實用的工具,可幫助我們更輕松地操作類型。如果要使用它們,你需要將類型傳遞給<>

Partial

  •  Partial<T>

Partial 允許你將T類型的所有屬性設為可選。它將在每一個字段后面添加一個?。 

  1. interface PartialType {  
  2.     id: number;  
  3.     firstName: string;  
  4.     lastName: string;  
  5.  
  6. /*  
  7. 等效于  
  8. interface PartialType {  
  9.   id?: number  
  10.   firstName?: string  
  11.   lastName?: string  
  12.  
  13. */ 
  14. function showType(args: Partial<PartialType>) {  
  15.     console.log(args);  
  16.  
  17. showType({ id: 1 });  
  18. // Output: {id: 1}  
  19. showType({ firstName: 'John', lastName: 'Doe' });  
  20. // Output: {firstName: "John", lastName: "Doe"} 

上面代碼中聲明了一個PartialType接口,它用作函數showType()的參數的類型。為了使所有字段都變為可選,我們使用Partial關鍵字并將PartialType類型作為參數傳遞。

Required

  •  Required<T>

將某個類型里的屬性全部變為必選項 

  1. interface RequiredType { 
  2.     id: number;  
  3.     firstName?: string;  
  4.     lastName?: string;  
  5.  
  6. function showType(args: Required<RequiredType>) {  
  7.     console.log(args);  
  8. showType({ id: 1, firstName: 'John', lastName: 'Doe' });  
  9. // Output: { id: 1, firstName: "John", lastName: "Doe" }  
  10. showType({ id: 1 });  
  11. // Error: Type '{ id: number: }' is missing the following properties from type 'Required<RequiredType>': firstName, lastName 

上面的代碼中,即使我們在使用接口之前先將某些屬性設為可選,但Required被加入后也會使所有屬性成為必選。如果省略某些必選參數,TypeScript 將報錯。

Readonly

  •  Readonly<T>

會轉換類型的所有屬性,以使它們無法被修改 

  1. interface ReadonlyType {  
  2.     id: number;  
  3.     name: string;  
  4.  
  5. function showType(args: Readonly<ReadonlyType>) {  
  6.     args.id = 4 
  7.     console.log(args);  
  8.  
  9. showType({ id: 1, name: 'Doe' });  
  10. // Error: Cannot assign to 'id' because it is a read-only property. 

我們使用Readonly來使ReadonlyType的屬性不可被修改。也就是說,如果你嘗試為這些字段之一賦予新值,則會引發錯誤。

除此之外,你還可以在指定的屬性前面使用關鍵字readonly使其無法被重新賦值 

  1. interface ReadonlyType {  
  2.     readonly id: number;  
  3.     name: string;  

Pick

  •  Pick<T, K>

此方法允許你從一個已存在的類型 T中選擇一些屬性作為K, 從而創建一個新類型

即 抽取一個類型/接口中的一些子集作為一個新的類型

T代表要抽取的對象 K有一個約束: 一定是來自T所有屬性字面量的聯合類型 新的類型/屬性一定要從K中選取, 

  1. /** 
  2.     源碼實現  
  3.  * From T, pick a set of properties whose keys are in the union K  
  4.  */  
  5. type Pick<T, K extends keyof T> = {  
  6.     [P in K]: T[P];  
  7. };  
  1. interface PickType {  
  2.     id: number;  
  3.     firstName: string;  
  4.     lastName: string;  
  5.  
  6. function showType(args: Pick<PickType, 'firstName' | 'lastName'>) {  
  7.     console.log(args);  
  8.  
  9. showType({ firstName: 'John', lastName: 'Doe' });  
  10. // Output: {firstName: "John"}  
  11. showType({ id: 3 });  
  12. // Error: Object literal may only specify known properties, and 'id' does not exist in type 'Pick<PickType, "firstName" | "lastName">

Pick 與我們前面討論的工具有一些不同,它需要兩個參數

  •  T是要從中選擇元素的類型
  •  K是要選擇的屬性(可以使使用聯合類型來選擇多個字段)

Omit

  • Omit<T, K>

Omit的作用與Pick類型正好相反。不是選擇元素,而是從類型T中刪除K個屬性。 

  1. interface PickType { 
  2.     id: number;  
  3.     firstName: string;  
  4.     lastName: string;  
  5.  
  6. function showType(args: Omit<PickType, 'firstName' | 'lastName'>) {  
  7.     console.log(args);  
  8.  
  9. showType({ id: 7 });  
  10. // Output: {id: 7}   
  11. showType({ firstName: 'John' });  
  12. // Error: Object literal may only specify known properties, and 'firstName' does not exist in type 'Pick<PickType, "id">

Extract

  •  Extract<T, U>

提取T中可以賦值給U的類型--取交集

Extract允許你通過選擇兩種不同類型中的共有屬性來構造新的類型。也就是從T中提取所有可分配給U的屬性。 

  1. interface FirstType { 
  2.     id: number;  
  3.     firstName: string;  
  4.     lastName: string;  
  5.  
  6. interface SecondType {  
  7.     id: number;  
  8.     address: string;  
  9.     city: string;  
  10.   
  11. type ExtractExtractType = Extract<keyof FirstType, keyof SecondType> 
  12. // Output: "id" 

在上面的代碼中,FirstType接口和SecondType接口,都存在 id:number屬性。因此,通過使用Extract,即提取出了新的類型 {id:number}。

Exclude

  •  Exclude<T, U> --從 T 中剔除可以賦值給 U 的類型。

與Extract不同,Exclude通過排除兩個不同類型中已經存在的共有屬性來構造新的類型。它會從T中排除所有可分配給U的字段。 

  1. interface FirstType {  
  2.     id: number;  
  3.     firstName: string;  
  4.     lastName: string;  
  5.  
  6. interface SecondType {  
  7.     id: number;  
  8.     address: string;  
  9.     city: string;  
  10.  
  11. type ExcludeExcludeType = Exclude<keyof FirstType, keyof SecondType> 
  12. // Output; "firstName" | "lastName" 

上面的代碼可以看到,屬性firstName和lastName 在SecondType類型中不存在。通過使用Extract關鍵字,我們可以獲得T中存在而U中不存在的字段。

Record

  •  Record<K,T>

此工具可幫助你構造具有給定類型T的一組屬性K的類型。將一個類型的屬性映射到另一個類型的屬性時,Record非常方便。 

  1. interface EmployeeType {  
  2.     id: number;  
  3.     fullname: string;  
  4.     role: string;  
  5.  
  6. let employees: Record<number, EmployeeType> = {  
  7.     0: { id: 1, fullname: 'John Doe', role: 'Designer' },  
  8.     1: { id: 2, fullname: 'Ibrahima Fall', role: 'Developer' },  
  9.     2: { id: 3, fullname: 'Sara Duckson', role: 'Developer' },  
  10. }; 
  11. // 0: { id: 1, fullname: "John Doe", role: "Designer" },  
  12. // 1: { id: 2, fullname: "Ibrahima Fall", role: "Developer" },  
  13. // 2: { id: 3, fullname: "Sara Duckson", role: "Developer" } 

Record的工作方式相對簡單。在代碼中,它期望一個number作為類型,這就是為什么我們將 0、1 和 2 作為employees變量的鍵的原因。如果你嘗試使用字符串作為屬性,則會引發錯誤,因為屬性是由EmployeeType給出的具有 ID,fullName 和 role 字段的對象。

NonNullable

  •  NonNullable<T>

    -- 從 T 中剔除 null 和 undefined 

  1. type NonNullableType = string | number | null | undefined;  
  2. function showType(args: NonNullable<NonNullableType>) {  
  3.     console.log(args);  
  4.  
  5. showType('test');  
  6. // Output: "test"  
  7. showType(1);  
  8. // Output: 1  
  9. showType(null);  
  10. // Error: Argument of type 'null' is not assignable to parameter of type 'string | number'.  
  11. showType(undefined);  
  12. // Error: Argument of type 'undefined' is not assignable to parameter of type 'string | number'. 

我們將類型NonNullableType作為參數傳遞給NonNullable,NonNullable通過排除null和undefined來構造新類型。也就是說,如果你傳遞可為空的值,TypeScript 將引發錯誤。

順便說一句,如果將--strictNullChecks標志添加到tsconfig文件,TypeScript 將應用非空性規則。

Mapped Types( 映射類型)

映射類型允許你從一個舊的類型,生成一個新的類型。

請注意,前面介紹的某些高級類型也是映射類型。如: 

  1. /*  
  2. Readonly, Partial和 Pick是同態的,但 Record不是。 因為 Record并不需要輸入類型來拷貝屬性,所以它不屬于同態:  
  3. */  
  4. type Readonly<T> = {  
  5.     readonly [P in keyof T]: T[P];  
  6. };  
  7. type Partial<T> = {  
  8.     [P in keyof T]?: T[P];  
  9. };  
  10. type Pick<T, K extends keyof T> = {  
  11.     [P in K]: T[P];  
  12. }; 

Record; 

  1. type StringMap<T> = {  
  2.     [P in keyof T]: string;  
  3. };  
  4. function showType(arg: StringMap<{ id: number; name: string }>) { 
  5.     console.log(arg); 
  6.  
  7. showType({ id: 1, name: 'Test' });  
  8. // Error: Type 'number' is not assignable to type 'string'.  
  9. showType({ id: 'testId', name: 'This is a Test' });  
  10. // Output: {id: "testId", name: "This is a Test"} 

StringMap<>會將傳入的任何類型轉換為字符串。就是說,如果我們在函數showType()中使用它,則接收到的參數必須是字符串-否則,TypeScript 將引發錯誤。

Type Guards(類型保護)

類型保護使你可以使用運算符檢查變量或對象的類型。這是一個條件塊,它使用typeof,instanceof或in返回類型。

typescript 能夠在特定區塊中保證變量屬于某種確定類型??梢栽诖藚^塊中放心地引用此類型的屬性,或者調用此類型的方法

typeof 

  1. function showType(x: number | string) {  
  2.     if (typeof x === 'number') {  
  3.         return `The result is ${x + x}`;  
  4.     }  
  5.     throw new Error(`This operation can't be done on a ${typeof x}`);  
  6.  
  7. showType("I'm not a number");  
  8. // Error: This operation can't be done on a string  
  9. showType(7);  
  10. // Output: The result is 14 

什么代碼中,有一個普通的 JavaScript 條件塊,通過typeof檢查接收到的參數的類型。

instanceof 

  1. class Foo {  
  2.     bar() {  
  3.         return 'Hello World';  
  4.     }  
  5.  
  6. class Bar {  
  7.     baz = '123' 
  8.  
  9. function showType(arg: Foo | Bar) {  
  10.     if (arg instanceof Foo) {  
  11.         console.log(arg.bar());  
  12.         return arg.bar();  
  13.     }  
  14.     throw new Error('The type is not supported');  
  15.  
  16. showType(new Foo());  
  17. // Output: Hello World   
  18. showType(new Bar());  
  19. // Error: The type is not supported 

像前面的示例一樣,這也是一個類型保護,它檢查接收到的參數是否是Foo類的一部分,并對其進行處理。

in 

  1. interface FirstType {  
  2.     x: number;  
  3.  
  4. interface SecondType {  
  5.     y: string;  
  6.  
  7. function showType(arg: FirstType | SecondType) {  
  8.     if ('x' in arg) {  
  9.         console.log(`The property ${arg.x} exists`);  
  10.         return `The property ${arg.x} exists`;  
  11.     }  
  12.     throw new Error('This type is not expected');  
  13.  
  14. showType({ x: 7 });  
  15. // Output: The property 7 exists  
  16. showType({ y: 'ccc' });  
  17. // Error: This type is not expected 

什么的栗子中,使用in檢查參數對象上是否存在屬性x。

Conditional Types(條件類型)

條件類型測試兩種類型,然后根據該測試的結果選擇其中一種。

一種由條件表達式所決定的類型, 表現形式為 T extends U ? X : Y , 即如果類型T可以被賦值給類型U,那么結果類型就是X類型,否則為Y類型。

條件類型使類型具有了不唯一性,增加了語言的靈活性, 

  1. // 源碼實現  
  2. type NonNullable<T> = T extends null | undefined ? never : T;  
  3. // NotNull<T> 等價于 NoneNullable<T,U>  
  4. // 用法示例  
  5. type resType = NonNullable<string | number | null | undefined>; // string|number  

上面的代碼中, NonNullable檢查類型是否為 null,并根據該類型進行處理。正如你所看到的,它使用了 JavaScript 三元運算符。 

 

責任編輯:龐桂玉 來源: 前端大全
相關推薦

2020-12-29 07:15:34

TypeScript語言代碼

2022-09-20 14:43:55

TypeScript類型體操

2009-06-12 09:15:04

EJB入門

2020-10-15 09:49:45

HarmonyOS 2設備開發

2021-12-10 08:21:15

TypeScript高級類型類型體操

2020-09-15 08:35:57

TypeScript JavaScript類型

2022-08-10 09:03:35

TypeScript前端

2021-02-19 23:55:15

PythonPythonic數據

2018-01-02 16:30:27

Python爬蟲微博移動端

2025-04-10 05:00:00

JavaScriptReactWeb

2009-09-25 13:48:17

Hibernate i

2010-06-08 16:23:22

UML教程

2010-09-28 09:33:25

DOM模型

2010-06-13 14:01:50

UML學習入門

2010-09-28 14:08:28

DOM

2017-05-16 14:48:24

WhatsApp數據安全

2010-07-20 13:19:16

Perl入門手冊

2009-09-24 15:03:30

Hibernate配置

2025-02-24 10:07:10

2009-08-14 13:52:18

C#判斷數據類型
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 永久精品| 超碰97人人人人人蜜桃 | 国产精品一区二区三区四区五区 | 欧美精品一区二区三区蜜桃视频 | 成人免费观看男女羞羞视频 | 亚洲精品视频一区 | 男女久久久 | 蜜桃视频一区二区三区 | 久草视频观看 | 欧美一级网站 | 国产一区二区三区在线 | 一区二区三区欧美 | 欧美在线日韩 | 国产1区2区3区 | 欧美日韩在线观看一区 | 国产在线不卡 | 国产精品完整版 | 成年免费在线观看 | 国产精品一区二区av | 91干b| 成年人在线观看视频 | 国产精品污污视频 | 91在线资源 | 久久国产精品-国产精品 | 91操操操 | 日韩在线播放一区 | 欧美日韩精品一区二区三区四区 | 久久首页 | 欧美亚洲国产一区二区三区 | 中文字幕一区二区三区四区五区 | 亚洲色图婷婷 | 国产一区免费视频 | 黄网站涩免费蜜桃网站 | 久久一区二区三区四区 | 欧美成人影院 | 男人av在线播放 | 国产成人jvid在线播放 | 久久精品国产免费 | 国产成人精品福利 | 不卡视频一区二区三区 | 国产免费一级一级 |