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

How to use TypeScript generics

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

Share

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

This article mainly shows you "how to use TypeScript generics", the content is easy to understand, clear, hope to help you solve doubts, the following let the editor lead you to study and learn "how to use TypeScript generics" this article.

1. Simple to use

Now we want to define a join function whose main function is to accept the same value of two types and return the concatenated value of the two parameters. The sample code is as follows:

/ / the so-called generics are generally defined as types / / define a join function that accepts two parameters of the same type, splices the two parameters and returns them. Function join (first: t, second: t) {return `${first} ${second}`} / / it is clear that T is the string type join ('first', 'second') / / first and second / / by type derivation, the compiler will automatically infer the type join (1, 2) / / 12 based on the passed parameters

Generics are defined by angle brackets. When we define the join function, we do not know which types can be accepted, but it is clear that the two types must be the same. If we want to meet such requirements, it is not so simple to solve without generics.

There are two ways to call the function, one is to specify the type as string directly, and the other is to deduce the type, and the editor will automatically help us determine the type based on the passed parameters.

two。 Using generics in functions

When defining a function, we can use multiple generics, and the return value type can also be specified by generics, as long as they correspond in quantity and usage.

The sample code is as follows:

Function identity (first: t, second: y, third: P): y {return second} / / specified type identity (true, 'string', 123) / / string / / type inference identity ('string', 123, true) / / true3. Using generics in classes

We can use generics not only in functions, but also in classes.

The sample code is as follows:

Class DataManager {/ / defines a class with a T-type private array constructor (private data: t []) {} / / the value getItem (index: number) in the array according to the index: t {return this.data [index]} const data = new DataManager (['one bowl week]) data.getItem (0) / / one bowl week

And generics can also be inherited from an interface. The sample code is as follows:

Interface Item {name: string} class DataManager {/ / defines a class with a T-type private array constructor (private data: t []) {} / / the values in the array getItem (index: number): string {return this.data [index] .name}} const data = new DataManager ([{name: 'bowl week']) data.getItem (0) / / one bowl week

Using extends can achieve the function of a generic constraint, in the case of the above code, we must constrain that the value passed in must have a name property, otherwise an exception will be thrown.

4. Using type parameters in generic constraints

If you have the following requirements, we define a class, a private object in the class that contains some properties, and then define a method to get its corresponding value through key.

The implementation code is as follows:

/ / define an interface interface Person {name: string age: number hobby: string} / / define a class class Me {constructor (private info: Person) {} getInfo (key: string) {return this.info [key]}} const me = new Me ({name: 'bowl week', age: 18, hobby: 'coding' }) / / call me.getInfo () and you may get a undefined as follows example me.getInfo ('myName') / / undefined

In the above code, if we call the getInfo () method in the sample object and pass in a property that we don't have, we get a undefined. This is not the style in TypeScript when a method is called to return a undefined.

This problem can be solved through the keyof operator, which can be used to get all keys of a certain type, whose return type is a union type.

The sample code is as follows:

Type myPerson = keyof Person / / 'name' |' age' | 'hobby'

Then the problem above can be solved by using this operator now.

The sample code is as follows:

Class Me {constructor (private info: Person) {} / / this is written in the same way as getInfo (key: t): Person [T] {return this.info [key]} / / getInfo (key: t): Person [T] {/ / return this.info [key] / /}} const me = new Me ({name: one bowl week, age: 18, hobby: 'coding' }) / / calling me.getInfo () compiles error me.getInfo ('myName') / / error: parameters of type "myName" cannot be assigned to parameters of type "keyof Person" if an unknown attribute is passed.

Now all we have to do is access properties that are not in the object and we will get an exception.

The above is all the contents of the article "how to use TypeScript generics". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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