In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >
Share
Shulou(Shulou.com)06/01 Report--
C # vs TypeScript-Advanced type
The previous article talked about basic types, which is basically enough for development, but if you want to develop more efficiently, you should take a look at advanced types. This article doesn't have much in common with C#, but extends this topic.
Joint type
It can be taken literally: it is actually a combination of multiple types, separated by the | symbol.
For example: string | number, indicating that you want this type to be either string or number.
Fields of federated types can only call methods that are common to those types unless the type inference system automatically determines the true type.
/ / here sn is a joint type field. Since type inference infers that sn must be string, sn can call all methods of string let sn: string | number = 'string, number';// cannot infer a specific type here, but can only call toString, toValue function snFunc (): string | number {return' string, number';}
Union types can be combined not only with basic types, but also with user-defined class, interace, and so on.
Cross type
Cross types are separated by the & symbol, which means that multiple types are put together, and the new type contains all the functions of the type.
Some languages such as Python have mixins functionality, which is easy to do with this, mainly similar to multiple inheritance, but individuals do not like this, which obviously violates the single principle.
The following code shows that mixins combines the functions of the two classes. It doesn't seem reasonable. The current trend is to combine first, and you can do the same with combinations.
Class Person {talk (): string {return `alone `;}} class Dog {bark (): string {return 'bark';}} function extend (first: t, second: U): t & U {let result = {}; for (let func of Object.getOwnPropertyNames (Object.getPrototypeOf (first) {(result) [func] = (first) [func] } for (let func of Object.getOwnPropertyNames (Object.getPrototypeOf (second) {(result) [func] = (second) [func];} return result;} let personDog = extend (new Person (), new Dog ()); console.info (personDog.talk ()); console.info (personDog.bark ()); Type conversion
One of the common type conversions in C # is the front parenthesis plus type, and the other is as.
TypeScript is the same as C #, except that parentheses are not changed to angle brackets.
Let test: any = '123 protectionlet str1: string = test;let str2: string = test as string; type protection
The union type returns one of several types, but you don't know which one it is when using it, and you need to judge one by one, which is troublesome.
Function get (): number | string {return 'test';} let test = get (); var len = test.length; / / cannot compile, do not know whether test is number or stringlet str =''; if ((test) .sub) {/ / string} else {/ / number}
In addition to judging whether it is string by whether there is a string-specific method, you can also use a typeof like C# to get its type, and it is important to provide a type protection mechanism
That is, you will know the type of this variable in the typeof scope.
Function get (): number | string {return 'test';} let test = get (); if (typeof test =' string') {console.info (test.length); / / since typeof determines that the test type is string, length can be fetched directly in the scope without having to be transferred.
Typeof comparison is limited. All the classes you create return object, so instanceof is used, and instanceof also provides type protection.
There are also type assertions that provide similar functionality, but not as convenient as the ones above.
Function get (): number | string {return 'test';} let test = get (); function isStr (p: number | string): p is string {return (p). Sub! = =' undefined';} if (isStr (test)) {console.info (test.length);} else {console.info (test + 1);}
The above p is string asserts that the parameter p is of type string, so that the type of test can be automatically obtained after isStr, and it is also known to be number type in else.
This is better than C #, which usually uses the as operator to turn around and then determine whether it is empty or not, which is complicated if there are many types.
Type alias
A type alias can give an existing type a new name.
Type newstring = string;let str: newstring = 'aaa';console.info (str.length)
You can also use using strList = System.Generic.List as an individual name in C #, but it is still different. C # can be instantiated.
The TypeScript alias is not a new type, but a reference to an existing type.
Aliasing the current type does not make much sense, but it can be combined with joint types or cross types to make some readable or relatively novel types.
Aliases also support generics, and now one has created a Tree type with an alias, but it's just an alias, it can't be instantiated, it can only be seen, which is not as real as the interface.
Class Chicken {} class Duck {} type Fowl = Chicken | Duck;type Tree = {value: t; left: Tree; right: Tree;} string literal type
TypeScript can make string a type, such as let strType = 'string type'.
This can be used in method parameters to limit the input of parameters.
Function test (param1: 'test1' |' test2' | 'test3') {} test (' test'); / / cannot be compiled. The parameter can only be test1, test2 or test3 recognizable combination.
Combining the above string literal types, union types, type protection, and type aliases, you can create a union-aware pattern.
You must have the same field in multiple custom classes, which use string literal types and combine these types.
Interface Square {kind: "square"; size: number;} interface Rectangle {kind: "rectangle"; width: number; height: number;} interface Circle {kind: "circle"; radius: number;} type Shape = Square | Rectangle | Circle;// here you can use identifiable joint function area (s: Shape) {case "square": return s.size * s.size Case "rectangle": return s.height * s.width; case "circle": return Math.PI * s.radius * * 2;}} type inference
TypeScript can infer the type of variable based on assignment or context, so sometimes it is not necessary to explicitly indicate the type of variable or function return value.
Let x = 123; / / if you can infer that x is number, you don't have to write it like this: let x: number = 123 function get () {return [1,2,3];} let arr = get (); / / it can also be inferred that arr is number []; function get () {return [1,'2, 3];} let arr = get (); / / it can be inferred here that arr is (number | string) []
However, I think that except for some obvious let x = 123s, it is best to write the type and increase the readability of the code.
These are the types of TypeScript, which are more flexible and difficult, and may be easier to master if you want to use them in actual projects.
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.