Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the advanced types of TypeScript

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "what are the advanced types of TypeScript". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Intersection Typ

Intersection types are a way to combine multiple types. This means that you can merge multiple types given and get a new type with all the attributes.

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

The "IntersectionType" in the code combines two types: LeftType and RightType, and uses the & symbol to construct the intersection intersection type.

Union Typ

The Union type is used to use different types of annotations in a given variable.

Type UnionType = string | number function showType (arg: UnionType) {console.log (arg)} showType ("test") / / Output: test showType (7) / / Output: 7

The showType function is a union type that accepts strings and numbers as arguments.

Paradigm type

Generic types are a way to reuse parts of a given type. It is used to handle the type T passed in by the parameter.

Function showType (args: t) {console.log (args)} showType ("test") / Output: "test" showType (1) / / Output: 1

To construct a generic type, you need to use angle brackets and pass T as an argument.

In the following code, I use the name T (the name is up to you), and then call the showType function twice with different type annotations because it is reusable.

Interface GenericType {id: number name: t} function showType (args: GenericType) {console.log (args)} showType ({id: 1, name: "test"}) / / Output: {id: 1, name: "test"} function showTypeTwo (args: GenericType) {console.log (args)} showTypeTwo ({id: 1, name: 4}) / / Output: {id: 1, name: 4}

There is another example, in which there is an interface GenericType that receives the common type T. Because it is reusable, we can call it with strings and numbers.

Interface GenericType {id: t name: U} function showType (args: GenericType) {console.log (args)} showType ({id: 1, name: "test"}) / / Output: {id: 1, name: "test"} function showTypeTwo (args: GenericType) {console.log (args)} showTypeTwo ({id: "001", name: ["This", "is", "a") "Test"]}) / / Output: {id: "001", name: Array ["This", "is", "a", "Test"]}

Generic types can receive multiple parameters. Pass in two parameters, T and U, in the example, and then use them as type comments for the property. That is, we can now give this interface and provide two different types as parameters.

Utility Typ

TypeScript provides convenient built-in utilities to help us easily manipulate types. The type to be processed needs to be passed to the.

(1) Partial

Partial

Partial allows you to make all properties of type T optional. Will it add one next to each field? Mark.

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

There is an interface called PartialType in the code, which serves as a type comment for the parameter of the function showType (). To make the property optional, you must use the Partial keyword and pass in the PartialType type as the parameter. Now all fields are optional.

(2) Required

Required

Unlike Partial, Required makes all attributes of type T required.

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

Even if you make them optional before, Required makes all eligible properties necessary. And TypeScript will raise an error if the attribute is omitted.

(3) Readonly

Readonly

This type converts all properties of type T so that they cannot be reassigned.

Interface ReadonlyType {id: number name: string} function showType (args: Readonly) {args.id = 4 console.log (args)} showType ({id: 1, name: "Doe"}) / / Error: cannot reassign 'id' because it is a read-only attribute.

Use Readonly in the code to make the properties of ReadonlyType non-reassignable. If you have to assign values to these fields, an error will be raised.

Besides that, you can also use the keyword readonly in front of a property to make it not reassignable. In addition, you can use the keyword "readonly" before the attribute so that it cannot be reassigned.

Interface ReadonlyType {readonly id: number name: string}

(4) Pick

Pick

It allows you to create a new type from the existing model T by selecting a type of attribute k.

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 is a little different from what you saw earlier. It requires two parameters-- T is the type of element to choose from, and k is the attribute to be selected. You can also use common pipe symbols (|) to separate them to select multiple fields.

(5) Omit

Omit

Omit is the opposite of Pick. It removes the K attribute from 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'

Omit works in a similar way to Pick.

(6) Extract

Extract

Extract allows you to construct a type by selecting attributes that appear in two different types. It extracts all the attributes that can be assigned to U from T.

Interface FirstType {id: number firstName: string lastName: string} interface SecondType {id: number address: string city: string} type ExtractExtractType = Extract / / Output: "id"

There is a common attribute id in the two interfaces in the code. Id can be extracted by Extract. If you have multiple shared fields, Extract will extract all similar properties.

(7) Exclude

Unlike Extract, Exclude constructs a type by excluding attributes that already exist in two different types. It excludes all fields that can be assigned to U.

Interface FirstType {id: number firstName: string lastName: string} interface SecondType {id: number address: string city: string} type ExcludeExcludeType = Exclude / / Output; "firstName" | "lastName"

In the above code, the attributes firstName and lastName can be assigned to the SecondType type because they don't exist there. These fields can be returned as expected through Extract.

(8) Record

Record

Record can help you construct a type that has a set of attributes K for a given type T. Record is handy when mapping attributes of one type to another.

Interface EmployeeType {id: number fullname: string role: string} let employees: Record = {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"}

The way Record works is relatively simple. In the code, it expects to use number as the type, which is why we use 0, 1, and 2 as keys for employees variables. If you try to use a string as a property, an error is thrown. Next, the property set is given by EmployeeType, so the object has fields id, fullName, and role.

(9) NonNullable

NonNullable

It allows you to remove null and undefined from type 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'.

In the code, NonNullableType is passed to NonNullable,NonNullable as an argument to construct a new type by excluding null and undefined from the type. That is, if you pass a nullable value, TypeScript will raise an error.

By the way, if you add the-- strictNullChecks flag to the tsconfig file, TypeScript will apply the non-null rule.

Mapping type

Mapping types allow you to take an existing model and convert each of its properties to a new type. Note that some of the utility types described earlier are also mapping types.

Type StringMap = {[P in keyof T]: string} function showType (arg: StringMap) {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 converts any type passed in to a string. That is, if you use it in the function showType (), the argument you receive must be a string, or TypeScript will report an error.

Type protection

Type protection allows you to check the type of a variable or object with an operator. It is actually a conditional block that checks the type returned with typeof, instanceof, or 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

There is a normal JavaScript conditional block in the code that checks the type of parameters detected by typeof. Your type is protected in this case.

(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

As in the previous example, this is also a type protection that checks whether the received parameter is part of the Foo class and handles it.

(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} Secrets`) return `The property ${arg.x} Secrets`} 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 the code, the in operator is used to check for the existence of attribute x on the object.

Conditional Typ

Used to test two types and select one of them according to the test results.

Type NonNullable = T extends null | undefined? Never: T

The NonNullable in this example checks whether the type is null and processes it according to that type.

This is the end of the content of "what are the advanced types of TypeScript". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report