In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge points of this article, "the combination of typeScript generic use and generic interface", so the editor summarizes the following, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this article, "the combination of typeScript generic use and generic interface" article.
The concept of generics, the use of generics, and the combination of generics and interfaces added to typeScript:
The problem of finding the minimum value may be encountered in practical application, such as finding the minimum value in the array.
In ts, you need to write in two ways, one for number and the other for strings.
Writing in this way is not conducive to code reuse, when the project is large, the performance is poor, and the work efficiency is low, so the concept of generics is introduced in ts.
Function getMin1 (arr:number []): number {let min = arr [0] for (var I = 1; I
< arr.length; i++){ if (min >Arr [I]) {min = arr [I]}} return min} console.log (getMin1 ([1,2,3,4])); function getMin2 (arr:string []): string {let min = arr [0] for (var I = 1; I
< arr.length; i++){ if (min >Arr [I]) {min = arr [I]}} return min} console.log (getMin2 (['a', 'baked,' c'])); 1. What is a generic?
Generics in English is generics, which means that when defining a function, interface, or class, you do not specify a specific type in advance, but specify a type when you use it.
How to define:
Function fnName (arg:T,...): t {return...}
Generic variables are usually represented by T, which can represent any type.
So, we can modify the above example to the following code:
Function getMin (arr: t []): t {let min = arr [0] for (var I = 1; I
< arr.length; i++){ if (min >Arr [I]) {min = arr [I]}} return min} getMin ([1,2,3,4]) getMin (['averse,' baked, 'cased,' d'])
In the above code, the main purpose of T is to help us capture the types passed in by the user, such as number or string. In addition, the compiler will automatically help us with type inference based on the passed parameters, and then set T to its type, so you can ignore the type input, such as:
GetMin ([1,2,3,4]) getMin (['averse,' baked, 'crested,' d'])
In some complex cases, to prevent the compiler from automatically inferring similar failures, pass in types as much as possible to prevent errors.
2. Generic types
What is the difference between the type of a generic function and that of a non-generic function?
They look very similar, and generic function types are preceded by a type parameter.
There are also the following features for generic function types:
A >, generic function types can have multiple parameters
Function fn (arg1: t, arg2: U) {return arg1}
B >, generic functions can use different generic parameter names
Function fn (arg1: t) {return arg1} let Fn: (arg1: M) = > M = fn
C >, you can define a generic function with the literal quantity of the object
Function fn (arg1: t) {return arg1} let Fn: {(arg: t): t} = fn3, generic interface
When defining a generic function using the literal quantity of an object, the form of the object can be replaced with the form of an interface and changed to:
Replace let Fn: {(arg: t): t} = fn// with interface FnInter {(arg: t): t} let Fn: FnInter = fn
There is a problem with this approach: the function knows nothing about the data type and cannot operate with a data type. So you need to improve and pass in the type as a parameter, such as:
Interface FnInter {(arg:T): t} let Fn: FnInter = fn
In this way we can clearly know which generic type is being used.
We use the entire interface as a generic parameter, which is called a generic interface. Its advantage is that we can clear the data types that know the parameters, and the members in the interface can also know the specific types of parameters.
4. Generic class
In addition to generic interfaces, there are interface classes. Generic classes are similar to generic functions.
The syntax format is:
Class name {} new class name () class GetMin {arr: t [] = [] add (ele:T) {this.arr.push (ele)} getMin (): t {var min = this.arr [0] for (var I = 0; I
< this.arr.length; i++){ if (min >This.arr [I]) {min = this.arr [I]} return min}} let gMin1 = new GetMin () gMin1.add (1) gMin1.add (5) console.log (gMin1.getMin ()); / / 1let gMin2 = new GetMin () gMin2.add ('a') gMin2.add ('b') console.log (gMin2.getMin ()); / / 25, generic constraint
Generics is really powerful, but it's not everything. For example:
Function getLength (val: t): number {return val.length;}
Error message indicates that the attribute "length" does not exist on type "T".
The reason is that only strings and arrays have length attributes, and there are no length attributes for numbers and objects, so an error has been reported. The solution is to ensure that the incoming data type has a length attribute, so you need to use generic constraints.
Generic constraints are mainly implemented through the interface + extends keyword.
Interface ILen {length:number} function getLength (val: t): number {return val.length;} console.log (getLength ("abcd")); console.log (getLength (1)); / / error prompt: type "number" does not satisfy the constraint "ILen".
The advantage of using generic constraints is that it helps us automatically detect whether the passed value matches the value of the constraint type, and there will be an error prompt when it is not satisfied.
6. Default type of generic parameters
After typeScript 2.3, you can specify a default type for type parameters in generics, which is used when no parameter type is specified when generics are used, and when the editor cannot infer the data type from the actual parameters.
Easy to use:
Interface P {name:T} let p1: P = {name: "little sister"} let p2: P = {name: 18}
The default types of generic parameters follow the following rules:
Type parameters with default types are considered optional.
The required type parameter cannot be after the optional type parameter.
If a type parameter has a constraint, the default type of the type parameter must satisfy this constraint.
When you specify a type argument, you only need to specify the type argument of the required type parameter. Unspecified type parameters are resolved to their default types.
If a default type is specified and type inference cannot select a candidate type, the default type is used as the inference result.
A declaration of a class or interface merged by an existing class or interface can introduce a default type for an existing type parameter.
A declaration of a class or interface merged by an existing class or interface can introduce a new type parameter, as long as it specifies the default type.
7. Generic conditional types
In typeScript 2.8, conditional types are introduced, and we can get different types according to certain conditions, which here are type compatibility constraints. Conditional types are introduced in ript 2.8.We can get different types according to certain conditions, which here are type compatibility constraints.
The conditional type detects the type relationship with a certain conditional expression, thus selecting one of the two types:
Use syntax:
T extends U? X: Y
The above expression means: if T can be assigned to U, then the type is X, otherwise it is Y.
The above is the content of this article on "the combination of typeScript generics and generic interfaces". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.