C # vs TypeScript-Advanced type
The previous article said the basic type, basically with the basic type enough to develop, but if you want to develop more efficiently, or to look at the high-level type, this and C # have little in common, just use this topic.
Union type
Can literally be understood: is actually multiple types of union together, |
separated by symbols.
such as: string | number
, expressed the hope that this type can be both string
, and can be number
.
A field of a union type can only invoke methods that are common to these types unless the type inference system automatically determines the true type.
//这里sn就是一个联合类型的字段,由于类型推论推断出sn肯定是string,所以sn可以调用string的所有方法let sn: string | number = ‘string, number‘;//这里就推断不出具体的类型,只能调用toString, toValue了function snFunc(): string | number{ return ‘string, number‘;}
Union types can be not only union primitives, but also user-definable class, interace
.
Cross type
Yes |
&
, the crossover type is separated by a &
symbol, which means that multiple types are combined and the new type contains all types of functionality.
Some languages, such as Python, are mixins
very easy to do with this, mostly similar to multiple inheritance, but individuals do not like this, clearly violating the single principle.
The following code shows a mixins
combination of two classes of functionality, it seems not a bit unreasonable, the current trend is also a combination of priority, with the same can be done with the combination.
Class Person {talk ():string {Return' A person '; }}Class Dog {bark ():string {Return' Wang Woo '; }}functionextend<TU> (First:t, Second:u):T &ULet result = <t & u>{};for (Let func of object.getownpropertynames (object.getprototypeof (first))) {(<any>result) [Func] = ( <Any>first) [func]; } for (Letfunc of object.getownpropertynames (object.getprototypeof (second))) {(<any> result) [Func] = (<any>second) [func];} return result;} Let Persondog = Extend (new person (), new Dog ()); Console.info (Persondog.talk ()); Console.info (Persondog.bark ());
Type conversions
A common type conversion in C # is a front parenthesis plus type, and one is as
.
Typescript, like C #, is not just parentheses into angle brackets.
let test: any = ‘123‘;let str1: string = <string>test;let str2: string = test as string;
Type protection
A union type returns one of several types, but it is cumbersome to use a judgment that does not know which one it is.
function Span class= "Hljs-title" >get (number | string{return ' test ';} let test = get (); var len = test.length; //not compile, do not know whether test is number or Stringlet str = if ((<string>test). Sub) { //string} else {//number}
In addition to a string-specific method to determine whether it is a string, it can be used similar to C # typeof
to get its type, and it is important to provide a type protection mechanism,
That is typeof
, the type of the variable is known in the scope.
function get(): number | string{ return ‘test‘;}let test = get();if(typeof test === ‘string‘){ console.info(test.length); // 这里由于typeof确定了test类型是string,所以作用域内可以直接取length,而不用<string>转一次}
typeof
The comparison is limited, and the classes that you create are returned, which are object
used instanceof
, and instanceof
also provide a type protection mechanism.
There are also types of assertions that can provide similar functionality, but not as convenient as the above.
functionGet):number | string{return ' test ';} let test = get (); function isstr (p: number | string): p is string{return (<string>p) . Sub!== ' undefined ';} if (ISSTR (test)) {console.info (test.length);} else {console.info (test + 1);}
Above is the assertion that the p is string
parameter p
is a type string
, which isStr
can be automatically obtained after the type test
, and else
also know is the number
type.
This is better than C #, the General C # approach may be to use the as
operator to turn around, and then determine whether it is empty, if the type is more complex operation.
Type aliases
Type aliases to take a new name for an existing type.
type newstring = string;let str: newstring = ‘aaa‘;console.info(str.length);
It can be used as an alias in C # using strList = System.Generic.List
, but it's still different, and C # can be instantiated.
The typescript alias is not a new type, but a reference to an existing type.
It is not very important to alias the current type, but it is possible to make some readable or relatively novel types with union type or cross type.
Aliases also support generics, there is now an alias to create a tree type, but also only aliases, not instantiated, can only be seen, this is not as good as the interface.
class Chicken{}class Duck{}type Fowl = Chicken | Duck;type Tree<T> = { value: T; left: Tree<T>; right: Tree<T>;}
string literal type
Typescript can make a string a type, for example 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‘); // 编译不了,参数只能是test1, test2或test3
Recognizable Union
Combining the above string literal type, union type, type protection, type alias can create a pattern that can identify the union.
You must have the same fields in the custom classes, which use the string literal type and combine the types.
Interface Square {kind:"Square"; Sizenumber;}Interface Rectangle {kind:"Rectangle"; WidthNumber Heightnumber;}interface Circle {kind: "Circle"; Radius: number;} type Shape = Square | Rectangle | Circle; //here can be used to identify the joint function area (s:shape) {switch (s.kind) {case "square": return s.size * s.size; Span class= "Hljs-keyword" >case "rectangle": return s.height * S.width; case "circle": return math.pi * S.radius * * 2;}
Type inference
Typescript can infer the type of a variable based on assignment or context, so it is sometimes possible not to explicitly indicate the type of the variable or function return value.
Let x =123;//here can infer that X is number, do not write this: let X:number = 123; function get ( return [1, 2, 3];} let arr = get (); //here can deduce that arr is number[]; function get ( return [1, ' 2 ', 3];} let arr = get (); //here can infer that arr is (number | string) [];
But personally think that in addition to some very obvious let x = 123
can not write, the other best is to write the type, increase the readability of the code.
The above is the type of typescript, more flexible and more difficult, may be in the actual project use will be better mastered.
From C # to typescript-Advanced types