<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          最強的高級TypeScript類型備忘單【含示例】

          共 7870字,需瀏覽 16分鐘

           ·

          2021-02-23 14:26

          文章來源:Dev

          文章地址:dev.to/ibrahima92/advanced-typescript-types-cheat-sheet-with-examples-5414


          關(guān)注公眾號?前端人,回復(fù)“加群

          添加無廣告優(yōu)質(zhì)學(xué)習(xí)群

          今天這篇ts文章,絕對的干貨滿滿,絕對的值得收藏,今天鬼哥強烈建議好好看看

          交叉點類型

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

          type?LeftType?=?{
          ??id:?number
          ??left:?string
          }

          type?RightType?=?{
          ??id:?number
          ??right:?string
          }

          type?IntersectionType?=?LeftType?&?RightType

          function?showType(args:?IntersectionType)?{
          ??console.log(args)
          }

          showType({?id:?1,?left:?"test",?right:?"test"?})
          //?Output:?{id:?1,?left:?"test",?right:?"test"}

          如您所見,IntersectionType將兩種類型組合在一起- LeftType,RightType然后使用&符號構(gòu)造交點類型。

          聯(lián)合類型

          聯(lián)合類型使您可以在給定變量中使用不同類型的注釋。

          type?UnionType?=?string?|?number

          function?showType(arg:?UnionType)?{
          ??console.log(arg)
          }

          showType("test")
          //?Output:?test

          showType(7)
          //?Output:?7

          該函數(shù)showType是聯(lián)合類型,它接受字符串和數(shù)字作為參數(shù)。

          通用類型

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

          function?showType<T>(args:?T)?{
          ??console.log(args)
          }

          showType("test")
          //?Output:?"test"

          showType(1)
          //?Output:?1

          要構(gòu)造泛型類型,您需要使用方括號并將其T作為參數(shù)傳遞。

          在這里,我使用T(名稱由您決定),然后showType使用不同的類型注釋兩次調(diào)用該函數(shù),因為它是通用的-可以重用。

          interface?GenericType?{
          ??id:?number
          ??name:?T
          }

          function?showType(args:?GenericType<string>)?{
          ??console.log(args)
          }

          showType({?id:?1,?name:?"test"?})
          //?Output:?{id:?1,?name:?"test"}

          function?showTypeTwo(args:?GenericType<number>)?{
          ??console.log(args)
          }

          showTypeTwo({?id:?1,?name:?4?})
          //?Output:?{id:?1,?name:?4}

          在這里,我們有另一個示例,該示例具有一個GenericType接收通用類型的接口T。由于它是可重用的,因此我們可以先使用字符串,然后使用數(shù)字來調(diào)用它。

          interface?GenericType?{
          ??id:?T
          ??name:?U
          }

          function?showType(args:?GenericType<number,?string>)?{
          ??console.log(args)
          }

          showType({?id:?1,?name:?"test"?})
          //?Output:?{id:?1,?name:?"test"}

          function?showTypeTwo(args:?GenericType<string,?string[]>)?{
          ??console.log(args)
          }

          showTypeTwo({?id:?"001",?name:?["This",?"is",?"a",?"Test"]?})
          //?Output:?{id:?"001",?name:?Array["This",?"is",?"a",?"Test"]}

          泛型類型可以接收多個參數(shù)。在這里,我們傳入兩個參數(shù):T和U,然后將它們用作屬性的類型注釋。也就是說,我們現(xiàn)在可以使用該接口并提供不同的類型作為參數(shù)。

          實用程序類型 TypeScript提供了方便的內(nèi)置實用程序,可幫助輕松地操作類型。要使用它們,您需要傳遞<>要轉(zhuǎn)換的類型。

          部分的

          Partial

          部分允許您將類型的所有屬性設(shè)為T可選。它將?在每個字段旁邊添加一個標(biāo)記。

          interface?PartialType?{
          ??id:?number
          ??firstName:?string
          ??lastName:?string
          }

          function?showType(args:?Partial)?{
          ??console.log(args)
          }

          showType({?id:?1?})
          //?Output:?{id:?1}

          showType({?firstName:?"John",?lastName:?"Doe"?})
          //?Output:?{firstName:?"John",?lastName:?"Doe"}

          如您所見,我們有一個接口PartialType,用作該函數(shù)接收的參數(shù)的類型注釋showType()。為了使屬性可選,我們必須使用Partial關(guān)鍵字并將類型PartialType作為參數(shù)傳遞。也就是說,現(xiàn)在所有字段都變?yōu)榭蛇x。

          必需的

          Required

          不同于Partial,該Required實用程序?qū)⑻峁㏕所需類型的所有屬性。

          interface?RequiredType?{
          ??id:?number
          ??firstName?:?string
          ??lastName?:?string
          }

          function?showType(args:?Required)?{
          ??console.log(args)
          }

          showType({?id:?1,?firstName:?"John",?lastName:?"Doe"?})
          //?Output:?{?id:?1,?firstName:?"John",?lastName:?"Doe"?}

          showType({?id:?1?})
          //?Error:?Type?'{?id:?number:?}'?is?missing?the?following?properties?from?type?'Required':?firstName,?lastName

          Required即使我們在使用該實用程序之前先將它們設(shè)為可選,該實用程序也會提供所有必需的屬性。而且,如果省略屬性,TypeScript將引發(fā)錯誤。

          只讀

          Readonly

          該實用程序類型將轉(zhuǎn)換該類型的所有屬性,T以使它們無法使用新值重新分配。

          interface?ReadonlyType?{
          id:?number
          name:?string
          }

          function?showType(args:?Readonly)?{
          args.id?=?4
          console.log(args)
          }

          showType({?id:?1,?name:?"Doe"?})
          //?Error:?Cannot?assign?to?'id'?because?it?is?a?read-only?property.

          在這里,我們使用該實用程序Readonly來使屬性ReadonlyType不能重新分配。也就是說,如果您嘗試為這些字段之一賦予新值,則會引發(fā)錯誤。

          除此之外,還可以readonly在屬性前面使用關(guān)鍵字,以使其無法重新分配。

          interface?ReadonlyType?{
          readonly?id:?number
          name:?string
          }

          挑選

          Pick

          它允許您T通過選擇現(xiàn)有類型的某些屬性K來從該模型創(chuàng)建新類型。

          interface?PickType?{
          id:?number
          firstName:?string
          lastName:?string
          }

          function?showType(args:?Pick)?{
          console.log(args)
          }

          showType({?firstName:?"John",?lastName:?"Doe"?})
          //?Output:?{firstName:?"John"}

          showType({?id:?3?})
          //?Error:?Object?literal?may?only?specify?known?properties,?and?'id'?does?not?exist?in?type?'Pick'

          Pick與我們已經(jīng)看到的以前的實用程序有些不同。它需要兩個參數(shù)-T是您要從中選擇元素的類型K,也是要選擇的屬性。您也可以通過使用pipe(|)符號將它們分開來選擇多個字段。

          忽略

          Omit

          該Omit實用程序與該Pick類型相反。而不是選擇元素,它將K從type中刪除屬性T。

          interface?PickType?{
          ??id:?number
          ??firstName:?string
          ??lastName:?string
          }

          function?showType(args:?Omit)?{
          ??console.log(args)
          }

          showType({?id:?7?})
          //?Output:?{id:?7}

          showType({?firstName:?"John"?})
          //?Error:?Object?literal?may?only?specify?known?properties,?and?'firstName'?does?not?exist?in?type?'Pick'

          此實用程序類似于Pick工作方式。它期望類型和屬性從該類型中省略。

          提煉

          Extract
          Extract允許您通過選擇兩種不同類型中存在的屬性來構(gòu)造類型。該實用程序?qū)腡可分配給的所有屬性中提取U。
          interface?FirstType?{
          id:?number
          firstName:?string
          lastName:?string
          }

          interface?SecondType?{
          id:?number
          address:?string
          city:?string
          }

          type?ExtractType?=?Extract
          //?Output:?"id"

          在這里,我們有兩種共同的特性id。因此,通過使用Extract關(guān)鍵字,我們可以返回該字段,id因為它同時存在于兩個接口中。并且,如果您有多個共享字段,該實用程序?qū)⑻崛∷邢嗨频膶傩浴?/p>

          排除

          與不同Extract,Exclude實用程序?qū)⑼ㄟ^排除已經(jīng)存在于兩種不同類型中的屬性來構(gòu)造類型。它從T可分配給的所有字段中排除U。

          interface?FirstType?{
          id:?number
          firstName:?string
          lastName:?string
          }

          interface?SecondType?{
          id:?number
          address:?string
          city:?string
          }

          type?ExcludeType?=?Exclude

          //?Output;?"firstName"?|?"lastName"

          如您所見,屬性firstName和lastName可分配給SecondType類型,因為它們在那里不存在。通過使用Extract關(guān)鍵字,我們可以按預(yù)期返回這些字段。

          記錄

          Record

          該實用程序可幫助您構(gòu)造K具有給定類型的一組屬性的類型T。Record在將一個類型的屬性映射到另一個類型的屬性時非常方便。

          interface?EmployeeType?{
          id:?number
          fullname:?string
          role:?string
          }

          let?employees:?Record<number,?EmployeeType>?=?{
          0:?{?id:?1,?fullname:?"John?Doe",?role:?"Designer"?},
          1:?{?id:?2,?fullname:?"Ibrahima?Fall",?role:?"Developer"?},
          2:?{?id:?3,?fullname:?"Sara?Duckson",?role:?"Developer"?},
          }

          //?0:?{?id:?1,?fullname:?"John?Doe",?role:?"Designer"?},
          //?1:?{?id:?2,?fullname:?"Ibrahima?Fall",?role:?"Developer"?},
          //?2:?{?id:?3,?fullname:?"Sara?Duckson",?role:?"Developer"?}

          該方法Record的作品是比較簡單的。在這里,它期望anumber作為類型,這就是為什么我們將0、1和2作為employees變量的鍵的原因。而且,如果您嘗試使用字符串作為屬性,則會引發(fā)錯誤。接下來,屬性集由EmployeeType具有字段id,fullName和role的對象給出。

          不可為空

          NonNullable

          它允許你刪除null,并undefined從類型T。

          type?NonNullableType?=?string?|?number?|?null?|?undefined

          function?showType(args:?NonNullable)?{
          console.log(args)
          }

          showType("test")
          //?Output:?"test"

          showType(1)
          //?Output:?1

          showType(null)
          //?Error:?Argument?of?type?'null'?is?not?assignable?to?parameter?of?type?'string?|?number'.

          showType(undefined)
          //?Error:?Argument?of?type?'undefined'?is?not?assignable?to?parameter?of?type?'string?|?number'.

          在這里,我們將類型NonNullableType作為參數(shù)傳遞給NonNullable實用程序,該實用程序通過從該類型中排除null和構(gòu)造該新undefined類型。也就是說,如果您傳遞可為空的值,TypeScript將引發(fā)錯誤。

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

          映射類型

          映射類型允許您采用現(xiàn)有模型并將其每個屬性轉(zhuǎn)換為新類型。請注意,前面介紹的某些實用程序類型也是映射類型。

          type?StringMap?=?{
          [P?in?keyof?T]:?string
          }

          function?showType(arg:?StringMap<{?id:?number;?name:?string?}>)?{
          console.log(arg)
          }

          showType({?id:?1,?name:?"Test"?})
          //?Error:?Type?'number'?is?not?assignable?to?type?'string'.

          showType({?id:?"testId",?name:?"This?is?a?Test"?})
          //?Output:?{id:?"testId",?name:?"This?is?a?Test"}

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

          類型防護

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

          typeof

          function?showType(x:?number?|?string)?{
          if?(typeof?x?===?"number")?{
          ??return?`The?result?is?${x?+?x}`
          }
          throw?new?Error(`This?operation?can't?be?done?on?a?${typeof?x}`)
          }

          showType("I'm?not?a?number")
          //?Error:?This?operation?can't?be?done?on?a?string

          showType(7)
          //?Output:?The?result?is?14

          如您所見,我們有一個普通的JavaScript條件塊,它檢查通過接收的參數(shù)的類型typeof。有了這個,您現(xiàn)在可以在這種情況下保護您的類型。

          instanceof

          class?Foo?{
          bar()?{
          ??return?"Hello?World"
          }
          }

          class?Bar?{
          baz?=?"123"
          }

          function?showType(arg:?Foo?|?Bar)?{
          if?(arg?instanceof?Foo)?{
          ??console.log(arg.bar())
          ??return?arg.bar()
          }

          throw?new?Error("The?type?is?not?supported")
          }

          showType(new?Foo())
          //?Output:?Hello?World

          showType(new?Bar())
          //?Error:?The?type?is?not?supported

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

          in

          interface?FirstType?{
          ??x:?number
          }
          interface?SecondType?{
          ??y:?string
          }

          function?showType(arg:?FirstType?|?SecondType)?{
          ??if?("x"?in?arg)?{
          ????console.log(`The?property?${arg.x}?exists`)
          ????return?`The?property?${arg.x}?exists`
          ??}
          ??throw?new?Error("This?type?is?not?expected")
          }

          showType({?x:?7?})
          //?Output:?The?property?7?exists

          showType({?y:?"ccc"?})
          //?Error:?This?type?is?not?expected

          該in允許你檢查屬性是否x收為參數(shù)的對象上存在與否。

          條件類型

          它測試兩種類型,并根據(jù)該測試的結(jié)果選擇其中一種。

          type?NonNullable?=?T?extends?null?|?undefined???never?:?T

          NonNullable實用程序類型的此示例檢查類型是否為null并根據(jù)該值進行處理。正如您所注意到的,它使用JavaScript三元運算符。

          • 回復(fù)資料包領(lǐng)取我整理的進階資料包
          • 回復(fù)加群,加入前端進階群
          • console.log("點贊===看===你我都快樂"
          • Bug離我更遠了,快樂離我更近了

          瀏覽 61
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  天天更新成人av 天天日天天操天天 | 影音先锋在线看片av一区 | 亚洲男人影院 | 高清无码操 | 大香蕉AAA |