日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
TypeScript高級(jí)類型入門手冊(cè):附大量代碼實(shí)例

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

創(chuàng)新互聯(lián)建站公司2013年成立,先為永興等服務(wù)建站,永興等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為永興企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。

你可以把本文看做一個(gè)帶有示例的 TypeScript 高級(jí)類型備忘單

讓我們開始吧!

Intersection Types(交叉類型)

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

 
 
 
  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,并使用&符號(hào)形成了交叉類型。

Union Types(聯(lián)合類型)

聯(lián)合類型使你可以賦予同一個(gè)變量不同的類型 

 
 
 
  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 

函數(shù)showType是一個(gè)聯(lián)合類型函數(shù),它接受字符串或者數(shù)字作為參數(shù)。

Generic Types(泛型)

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

優(yōu)點(diǎn): 創(chuàng)建可重用的函數(shù),一個(gè)函數(shù)可以支持多種類型的數(shù)據(jù)。這樣開發(fā)者就可以根據(jù)自己的數(shù)據(jù)類型來使用函數(shù)

泛型函數(shù) 

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

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

我們把 showType 函數(shù)叫做泛型函數(shù),因?yàn)樗梢赃m用于多個(gè)類型

泛型接口 

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

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

注:泛型變量約束了整個(gè)接口后,在實(shí)現(xiàn)的時(shí)候,必須指定一個(gè)類型

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

多參數(shù)的泛型類型 

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

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

Utility Types

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

Partial

  •  Partial

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

 
 
 
  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) {  
  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"} 

上面代碼中聲明了一個(gè)PartialType接口,它用作函數(shù)showType()的參數(shù)的類型。為了使所有字段都變?yōu)榭蛇x,我們使用Partial關(guān)鍵字并將PartialType類型作為參數(shù)傳遞。

Required

  •  Required

將某個(gè)類型里的屬性全部變?yōu)楸剡x項(xiàng) 

 
 
 
  1. interface RequiredType { 
  2.     id: number;  
  3.     firstName?: string;  
  4.     lastName?: string;  
  5. }  
  6. function showType(args: Required) {  
  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': firstName, lastName 

上面的代碼中,即使我們?cè)谑褂媒涌谥跋葘⒛承傩栽O(shè)為可選,但Required被加入后也會(huì)使所有屬性成為必選。如果省略某些必選參數(shù),TypeScript 將報(bào)錯(cuò)。

Readonly

  •  Readonly

會(huì)轉(zhuǎn)換類型的所有屬性,以使它們無法被修改 

 
 
 
  1. interface ReadonlyType {  
  2.     id: number;  
  3.     name: string;  
  4. }  
  5. function showType(args: Readonly) {  
  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的屬性不可被修改。也就是說,如果你嘗試為這些字段之一賦予新值,則會(huì)引發(fā)錯(cuò)誤。

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

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

Pick

  •  Pick

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

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

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

 
 
 
  1. /** 
  2.     源碼實(shí)現(xiàn)  
  3.  * From T, pick a set of properties whose keys are in the union K  
  4.  */  
  5. type Pick = {  
  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) {  
  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

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

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

Omit

  • Omit

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

 
 
 
  1. interface PickType { 
  2.     id: number;  
  3.     firstName: string;  
  4.     lastName: string;  
  5. }  
  6. function showType(args: Omit) {  
  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

Extract

  •  Extract

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

Extract允許你通過選擇兩種不同類型中的共有屬性來構(gòu)造新的類型。也就是從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;  
  12. // Output: "id" 

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

Exclude

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

與Extract不同,Exclude通過排除兩個(gè)不同類型中已經(jīng)存在的共有屬性來構(gòu)造新的類型。它會(huì)從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;  
  12. // Output; "firstName" | "lastName" 

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

Record

  •  Record

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

 
 
 
  1. interface EmployeeType {  
  2.     id: number;  
  3.     fullname: string;  
  4.     role: string;  
  5. }  
  6. let employees: Record = {  
  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的工作方式相對(duì)簡(jiǎn)單。在代碼中,它期望一個(gè)number作為類型,這就是為什么我們將 0、1 和 2 作為employees變量的鍵的原因。如果你嘗試使用字符串作為屬性,則會(huì)引發(fā)錯(cuò)誤,因?yàn)閷傩允怯蒃mployeeType給出的具有 ID,fullName 和 role 字段的對(duì)象。

NonNullable

  •  NonNullable

    -- 從 T 中剔除 null 和 undefined 

 
 
 
  1. type NonNullableType = string | number | null | undefined;  
  2. function showType(args: NonNullable) {  
  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作為參數(shù)傳遞給NonNullable,NonNullable通過排除null和undefined來構(gòu)造新類型。也就是說,如果你傳遞可為空的值,TypeScript 將引發(fā)錯(cuò)誤。

順便說一句,如果將--strictNullChecks標(biāo)志添加到tsconfig文件,TypeScript 將應(yīng)用非空性規(guī)則。

Mapped Types( 映射類型)

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

請(qǐng)注意,前面介紹的某些高級(jí)類型也是映射類型。如: 

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

Record; 

 
 
 
  1. type StringMap = {  
  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<>會(huì)將傳入的任何類型轉(zhuǎn)換為字符串。就是說,如果我們?cè)诤瘮?shù)showType()中使用它,則接收到的參數(shù)必須是字符串-否則,TypeScript 將引發(fā)錯(cuò)誤。

Type Guards(類型保護(hù))

類型保護(hù)使你可以使用運(yùn)算符檢查變量或?qū)ο蟮念愋汀_@是一個(gè)條件塊,它使用typeof,instanceof或in返回類型。

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

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 

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

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 

像前面的示例一樣,這也是一個(gè)類型保護(hù),它檢查接收到的參數(shù)是否是Foo類的一部分,并對(duì)其進(jìn)行處理。

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檢查參數(shù)對(duì)象上是否存在屬性x。

Conditional Types(條件類型)

條件類型測(cè)試兩種類型,然后根據(jù)該測(cè)試的結(jié)果選擇其中一種。

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

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

 
 
 
  1. // 源碼實(shí)現(xiàn)  
  2. type NonNullable = T extends null | undefined ? never : T;  
  3. // NotNull 等價(jià)于 NoneNullable  
  4. // 用法示例  
  5. type resType = NonNullable; // string|number  

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


當(dāng)前題目:TypeScript高級(jí)類型入門手冊(cè):附大量代碼實(shí)例
當(dāng)前URL:http://www.dlmjj.cn/article/djcpjgh.html