自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

TypeScript 高級類型總結(jié)(含代碼案例)

開發(fā) 前端
TypeScript 是一種類型化的語言,允許你指定變量、函數(shù)參數(shù)、返回的值和對象屬性的類型。以下是 TypeScript 高級類型的使用方法總結(jié),而且?guī)в欣印?/div>

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

以下是 TypeScript 高級類型的使用方法總結(jié),而且?guī)в欣印?/p>

[[360722]]

Intersection 類型

Intersection 類型是一種把對多種類型進(jìn)行組合的方法。這意味著你可以把給定的多種類型合并,并得到一個帶有全部屬性的新類型。

  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.  
  11. function showType(args: IntersectionType) { 
  12.   console.log(args) 
  13.  
  14. showType({ id: 1, left: "test", right: "test" }) 
  15. // Output: {id: 1, left: "test", right: "test"} 

代碼中的 IntersectionType ”組合了兩種類型:LeftType 和 RightType,并使用 & 符號來構(gòu)造交 intersection 類型。

Union 類型

Union 類型用來在給定變量中使用不同類型的注釋。

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

showType 函數(shù)是一個 union 類型,它能夠接受字符串和數(shù)字作為參數(shù)。

范型類型

泛型類型是一種用來重用給定類型的一部分的方式。它用來處理參數(shù)傳入的類型 T。

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

要構(gòu)造一個泛型類型,需要用到尖括號并將 T 作為參數(shù)進(jìn)行傳遞。

在下面的代碼中,我用的是 T(這個名稱隨你決定)這個名字,然后使用不同的類型注釋調(diào)用了兩次 showType 函數(shù),因?yàn)樗强梢灾赜玫摹?/p>

  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.  
  11. function showTypeTwo(args: GenericType<number>) { 
  12.   console.log(args) 
  13.  
  14. showTypeTwo({ id: 1, name: 4 }) 
  15. // Output: {id: 1, name: 4} 

還有另一個例子,例子中有一個接口 GenericType,這個接口接收通用類型 T。由于它是可重用的,因此我們可以用字符串和數(shù)字來調(diào)用它。

  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.  
  11. function showTypeTwo(args: GenericType<string, string[]>) { 
  12.   console.log(args) 
  13.  
  14. showTypeTwo({ id: "001", name: ["This", "is", "a", "Test"] }) 
  15. // Output: {id: "001", name: Array["This", "is", "a", "Test"]} 

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

實(shí)用工具類型

TypeScript 提供了方便的內(nèi)置實(shí)用工具,可幫助我們輕松地操作類型。在使用時需要將要處理的類型傳遞給 <>。

(1) Partial

Partial<T>

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

  1. interface PartialType { 
  2.   id: number 
  3.   firstName: string 
  4.   lastName: string 
  5.  
  6. function showType(args: Partial<PartialType>) { 
  7.   console.log(args) 
  8.  
  9. showType({ id: 1 }) 
  10. // Output: {id: 1} 
  11.  
  12. showType({ firstName: "John", lastName: "Doe" }) 
  13. // Output: {firstName: "John", lastName: "Doe"} 

代碼中有一個名為 PartialType 的接口,它作為函數(shù) showType() 的參數(shù)的類型注釋。要想使屬性是可選的,必須用到 Partial 關(guān)鍵字,并傳入 PartialType 類型作為參數(shù)?,F(xiàn)在所有字段都變成了可選的。

(2) Required

Required<T>

與 Partial 不同,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.  
  9. showType({ id: 1, firstName: "John", lastName: "Doe" }) 
  10. // Output: { id: 1, firstName: "John", lastName: "Doe" } 
  11.  
  12. showType({ id: 1 }) 
  13. // Error: Type '{ id: number: }' is missing the following properties from type 'Required<RequiredType>': firstName, lastName 

即使在之前先將它們設(shè)為可選的,Required 也會使所有符合條件的屬性成為必需的。而且如果省略掉屬性的話TypeScript 將會引發(fā)錯誤。

(3) Readonly

Readonly<T>

這個類型會對所有類型為 T 的屬性進(jìn)行轉(zhuǎn)換,使它們無法被重新賦值。

  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: 無法給'id'重新賦值,因?yàn)樗侵蛔x屬性。 

在代碼中用 Readonly 來使 ReadonlyType 的屬性不可被重新賦值。如果你一定要為這些字段賦值的話,將會引發(fā)錯誤。

Besides that, you can also use the keyword readonly in front of a property to make it not reassignable. 除此之外,還可以在屬性前面使用關(guān)鍵字“ readonly”,以使其無法重新分配。

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

(4) Pick

Pick<T,K>

它允許你通過選擇某個類型的屬性 k ,從現(xiàn)有的模型 T 中創(chuàng)建一個新類型。

  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.  
  12. showType({ id: 3 }) 
  13. // Error: Object literal may only specify known properties, and 'id' does not exist in type 'Pick<PickType, "firstName" | "lastName">

Pick 與前面看到的那些有點(diǎn)不同。它需要兩個參數(shù) —— T 是要從中選擇元素的類型,k 是要選擇的屬性。還可以通用管道符號 (|)將它們分開來選擇多個字段。

(5) 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.  
  12. showType({ firstName: "John" }) 
  13. // Error: Object literal may only specify known properties, and 'firstName' does not exist in type 'Pick<PickType, "id">

Omit 的工作方式與 Pick 類似。

(6) Extract

Extract<T,U>

Extract 使你通過選擇出現(xiàn)在兩個不同類型中的屬性來構(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<keyof FirstType, keyof SecondType> 
  12. // Output: "id" 

在代碼中的兩個接口里有共有的屬性 id。通過 Extract 可以把 id 提取出來。如果你有多個共享字段,Extract 將會提取所有相似的屬性。

(7) Exclude

與 Extract 不同,Exclude 通過排除已經(jīng)存在于兩個不同類型中的屬性來構(gòu)造類型。它排除了所有可以分配給 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.  
  13. // Output; "firstName" | "lastName" 

在上面的代碼中,屬性 firstName 和 lastName 可分配給 SecondType 類型,因?yàn)樗鼈冊谀抢锊淮嬖凇Mㄟ^ Extract 可以按預(yù)期返回這些字段。

(8) Record

Record<K,T>

Record 可以幫你構(gòu)造一個類型,該類型具有給定類型 T 的一組屬性 K。當(dāng)把一個類型的屬性映射到另一個類型時,用 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 變量的鍵的原因。如果試圖將字符串用作屬性,則會引發(fā)錯誤。接下來,屬性集由 EmployeeType 給出,因此該對象具有字段 id、 fullName 和 role。

(9) NonNullable

NonNullable<T>

它允許你從類型 T 中刪除 null 和 undefined。

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

在代碼中吧 NonNullableType 作為參數(shù)傳給了 NonNullable,NonNullable通過從該類型中排除 null 和 undefined 來構(gòu)造新類型。也就是說,如果你傳遞可空的值,TypeScript 將會引發(fā)錯誤。

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

映射類型

映射類型允許你獲取現(xiàn)有模型并將其每個屬性轉(zhuǎn)換為新類型。注意,前面介紹的一些實(shí)用工具類型也是映射類型。

  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.  
  10. showType({ id: "testId", name: "This is a Test" }) 
  11. // Output: {id: "testId", name: "This is a Test"} 

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

類型保護(hù)

類型保護(hù)使你可以用運(yùn)算符檢查變量或?qū)ο蟮念愋?。它?shí)際上是一個檢查用 typeof、instanceof 或 in 所返回類型的條件塊。

(1) typeoff

  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.  
  10. showType(7) 
  11. // Output: The result is 14 

代碼中有一個普通的 JavaScript 條件塊,該塊檢查通過 typeof 檢測到的參數(shù)的類型。在這種情況下就保護(hù)你的類型了。

(2) 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.  
  15.   throw new Error("The type is not supported") 
  16.  
  17. showType(new Foo()) 
  18. // Output: Hello World 
  19.  
  20. showType(new Bar()) 
  21. // Error: The type is not supported 

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

(3) in

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

在代碼中,in 運(yùn)算符用來檢查對象上是否存在屬性 x。

Conditional 類型

用來對兩種類型進(jìn)行測試,并根據(jù)測試的結(jié)果選擇其中的一種。

  1. type NonNullable<T> = T extends null | undefined ? never : T 

這個例子中的 NonNullable 檢查該類型是否為 null 并根據(jù)該類型進(jìn)行處理。

 

責(zé)任編輯:趙寧寧 來源: 前端先鋒
相關(guān)推薦

2021-08-24 13:05:25

TypeScript代碼前端

2022-09-20 14:43:55

TypeScript類型體操

2022-03-09 20:18:49

TypeScript類型函數(shù)

2021-12-10 08:21:15

TypeScript高級類型類型體操

2020-09-15 08:35:57

TypeScript JavaScript類型

2022-08-10 09:03:35

TypeScript前端

2020-11-18 13:52:55

彈窗APP界面

2025-04-10 05:00:00

JavaScriptReactWeb

2019-08-28 11:08:51

排序算法Java

2022-02-25 09:06:02

TypeScripnever工具

2021-07-27 06:06:34

TypeScript語言運(yùn)算符

2022-05-04 09:02:41

TypeScript類型工具

2021-01-06 14:42:09

前端Typescript代碼

2019-12-13 10:24:05

PythonSQL注入ORM注入

2023-03-28 09:56:47

TypeScripJavaScrip

2021-08-04 09:32:05

Typescript 技巧Partial

2011-04-06 09:50:56

2021-05-26 10:40:28

Vue3TypeScript前端

2021-08-02 06:56:19

TypeScript編程語言編譯器

2021-08-18 07:56:05

Typescript類型本質(zhì)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號