TypeScript 高級類型總結(jié)(含代碼案例)
TypeScript 是一種類型化的語言,允許你指定變量、函數(shù)參數(shù)、返回的值和對象屬性的類型。
以下是 TypeScript 高級類型的使用方法總結(jié),而且?guī)в欣印?/p>
Intersection 類型
Intersection 類型是一種把對多種類型進(jìn)行組合的方法。這意味著你可以把給定的多種類型合并,并得到一個帶有全部屬性的新類型。
- 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)造交 intersection 類型。
Union 類型
Union 類型用來在給定變量中使用不同類型的注釋。
- type UnionType = string | number
- function showType(arg: UnionType) {
- console.log(arg)
- }
- showType("test")
- // Output: test
- showType(7)
- // Output: 7
showType 函數(shù)是一個 union 類型,它能夠接受字符串和數(shù)字作為參數(shù)。
范型類型
泛型類型是一種用來重用給定類型的一部分的方式。它用來處理參數(shù)傳入的類型 T。
- function showType<T>(args: T) {
- console.log(args)
- }
- showType("test")
- // Output: "test"
- showType(1)
- // Output: 1
要構(gòu)造一個泛型類型,需要用到尖括號并將 T 作為參數(shù)進(jìn)行傳遞。
在下面的代碼中,我用的是 T(這個名稱隨你決定)這個名字,然后使用不同的類型注釋調(diào)用了兩次 showType 函數(shù),因?yàn)樗强梢灾赜玫摹?/p>
- interface GenericType<T> {
- 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<T, U> {
- 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ù)。
實(shí)用工具類型
TypeScript 提供了方便的內(nèi)置實(shí)用工具,可幫助我們輕松地操作類型。在使用時需要將要處理的類型傳遞給 <>。
(1) Partial
Partial<T>
- interface PartialType {
- id: number
- firstName: string
- lastName: string
- }
- function showType(args: Partial<PartialType>) {
- console.log(args)
- }
- showType({ id: 1 })
- // Output: {id: 1}
- showType({ firstName: "John", lastName: "Doe" })
- // Output: {firstName: "John", lastName: "Doe"}
代碼中有一個名為 PartialType 的接口,它作為函數(shù) showType() 的參數(shù)的類型注釋。要想使屬性是可選的,必須用到 Partial 關(guān)鍵字,并傳入 PartialType 類型作為參數(shù)?,F(xiàn)在所有字段都變成了可選的。
(2) Required
Required<T>
- interface RequiredType {
- id: number
- firstName?: string
- lastName?: string
- }
- function showType(args: Required<RequiredType>) {
- 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<RequiredType>': firstName, lastName
即使在之前先將它們設(shè)為可選的,Required 也會使所有符合條件的屬性成為必需的。而且如果省略掉屬性的話TypeScript 將會引發(fā)錯誤。
(3) Readonly
Readonly<T>
這個類型會對所有類型為 T 的屬性進(jìn)行轉(zhuǎn)換,使它們無法被重新賦值。
- interface ReadonlyType {
- id: number
- name: string
- }
- function showType(args: Readonly<ReadonlyType>) {
- args.id = 4
- console.log(args)
- }
- showType({ id: 1, name: "Doe" })
- // 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”,以使其無法重新分配。
- interface ReadonlyType {
- readonly id: number
- name: string
- }
(4) Pick
Pick<T,K>
它允許你通過選擇某個類型的屬性 k ,從現(xiàn)有的模型 T 中創(chuàng)建一個新類型。
- interface PickType {
- id: number
- firstName: string
- lastName: string
- }
- function showType(args: Pick<PickType, "firstName" | "lastName">) {
- 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<PickType, "firstName" | "lastName">'
Pick 與前面看到的那些有點(diǎn)不同。它需要兩個參數(shù) —— T 是要從中選擇元素的類型,k 是要選擇的屬性。還可以通用管道符號 (|)將它們分開來選擇多個字段。
(5) Omit
Omit<T,K>
Omit 與Pick 相反。它從類型 T 中刪除 K 屬性。
- interface PickType {
- id: number
- firstName: string
- lastName: string
- }
- function showType(args: Omit<PickType, "firstName" | "lastName">) {
- 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<PickType, "id">'
Omit 的工作方式與 Pick 類似。
(6) Extract
Extract<T,U>
Extract 使你通過選擇出現(xiàn)在兩個不同類型中的屬性來構(gòu)造類型。它從 T 中提取所有可分配給 U 的屬性。
- interface FirstType {
- id: number
- firstName: string
- lastName: string
- }
- interface SecondType {
- id: number
- address: string
- city: string
- }
- type ExtractExtractType = Extract<keyof FirstType, keyof SecondType>
- // Output: "id"
在代碼中的兩個接口里有共有的屬性 id。通過 Extract 可以把 id 提取出來。如果你有多個共享字段,Extract 將會提取所有相似的屬性。
(7) Exclude
與 Extract 不同,Exclude 通過排除已經(jīng)存在于兩個不同類型中的屬性來構(gòu)造類型。它排除了所有可以分配給 U 的字段。
- interface FirstType {
- id: number
- firstName: string
- lastName: string
- }
- interface SecondType {
- id: number
- address: string
- city: string
- }
- type ExcludeExcludeType = Exclude<keyof FirstType, keyof SecondType>
- // Output; "firstName" | "lastName"
在上面的代碼中,屬性 firstName 和 lastName 可分配給 SecondType 類型,因?yàn)樗鼈冊谀抢锊淮嬖凇Mㄟ^ Extract 可以按預(yù)期返回這些字段。
(8) Record
Record<K,T>
Record 可以幫你構(gòu)造一個類型,該類型具有給定類型 T 的一組屬性 K。當(dāng)把一個類型的屬性映射到另一個類型時,用 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 的工作方式相對簡單。在代碼中,它期望用 number 作為類型,這就是我們把 0、1 和 2 作為 employees 變量的鍵的原因。如果試圖將字符串用作屬性,則會引發(fā)錯誤。接下來,屬性集由 EmployeeType 給出,因此該對象具有字段 id、 fullName 和 role。
(9) NonNullable
NonNullable<T>
- type NonNullableType = string | number | null | undefined
- function showType(args: NonNullable<NonNullableType>) {
- 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,NonNullable通過從該類型中排除 null 和 undefined 來構(gòu)造新類型。也就是說,如果你傳遞可空的值,TypeScript 將會引發(fā)錯誤。
順便說一句,如果把 --strictNullChecks 標(biāo)志添加到 tsconfig 文件,TypeScript 將應(yīng)用非空性規(guī)則。
映射類型
映射類型允許你獲取現(xiàn)有模型并將其每個屬性轉(zhuǎn)換為新類型。注意,前面介紹的一些實(shí)用工具類型也是映射類型。
- type StringMap<T> = {
- [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 將會報錯。
類型保護(hù)
類型保護(hù)使你可以用運(yùn)算符檢查變量或?qū)ο蟮念愋?。它?shí)際上是一個檢查用 typeof、instanceof 或 in 所返回類型的條件塊。
(1) typeoff
- 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 條件塊,該塊檢查通過 typeof 檢測到的參數(shù)的類型。在這種情況下就保護(hù)你的類型了。
(2) 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
和像前面的例子一樣,這也是一個類型保護(hù),它檢查接收到的參數(shù)是否為 Foo 類的一部分,并對其進(jìn)行處理。
(3) 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 運(yùn)算符用來檢查對象上是否存在屬性 x。
Conditional 類型
用來對兩種類型進(jìn)行測試,并根據(jù)測試的結(jié)果選擇其中的一種。
- type NonNullable<T> = T extends null | undefined ? never : T
這個例子中的 NonNullable 檢查該類型是否為 null 并根據(jù)該類型進(jìn)行處理。


2011-04-06 09:50:56




