TypeScript entry two: the basic data types

  • On the basic data types
  • TypeScript type resolution

 I. Analysis of basic data types

First, there is a problem TypeScript is a compiled language? Or interpreted language? The two apparently can not be divided into categories, TypeScript is not to allow JavaScript to change the implementation, not in order to improve the efficiency of the machine. The compiled and interpreted classification is based on these two characteristics. However, TypeScript have a compiled language features, it is the type of inspection, if the type of conflict that it can not be compiled into a js file.

Since TypeScript compiler requires variable type checking, which means that TypeScript variables are typed in front of it might make you're wondering, JavaScript before again TypeScript not type? String, Number, boolean, etc. are not type?

JavaScript variable itself is not really the type of concept exists, but there is just the type of the variable's value, change the type of the variable itself takes place along with the types of values. The variable TypeScript is typed, and it's no longer the type of change with the type of values ​​occurs, the editor have appeared in error checking variable and value types inconsistencies will prompt an error, and this is the key to understanding TypeScript ,Very important.

TypeScript include basic types: boolean values, numbers, strings, arrays, tuples, enumeration, Any, Void, Null, Undefined, Never, Object.

Before the next content recommendation aware of the following

JavaScript strict mode, related blog: JavaScript strict mode

JavaScript type conversions, related blog: type and native function and type conversion (III: End of js type conversion)

ES6 variable declaration: ES6 Getting Started: block-level scope (let & const), spread expansion, rest collection

Learn more about ES6 syntax here: All analytical content on ES6 syntax and API's

Suggested Reading TtpeScript variable declaration document (its brief resolved ES5 and ES6 variable declarations related content): variable declarations of official documents

 Two, TypeScript type resolution

1.TypeScript basic data types:

TypeScript data type is used to describe the variable itself, with the type of the variable itself and the type of constraint value, when the type of the value does not match the type of the variable itself, the IDE will prompt an error.

Declaratively 1.1 boolean, numeric, string variable syntax:

let the variable name: variable type = value; // type of the value must match the variable type, otherwise an error

Example:

1 let isDone: boolean = false; 
2 let decLiteral: number = 6; 
3 let hexLiteral: number = 0xf00d; //16进制
4 let binaryLiteral: number = 0b1010; //二进制
5 let octalLiteral: number = 0o744; //8进制
6 let name: string = "bob";

Custom template string:

. 1 the let name: String = `Gene`;
 2 the let Age: Number = 37 [ ;
 . 3  // template string using the backquote (`) package, using embedded expression $ {expr} 
. 4 the let sentence: String = `the Hello, My IS $ {name} name.
 . 5 the I'll BE $ {Old Age years +. 1} Next month.`;

1.2 arrays, tuples, enumeration

1  // array 
2 the let List: Number [] = [l, 2,3]; // List variable is an array, the array is no problem as long as the assignment 
. 3 the let numlist: the Array <Number> = [l, 2,3] ; // generic array, each element of the array must conform to the specified type of assignment of the generic type 
. 4 the let strlist: the array <String> = [ ". 1", "2", ". 3"]; // this is a character generic string array

There is also a shorthand way a generic array:

let names: string [] = [ 'Bob', 'red'];

About Generics for the official document: https://www.tslang.cn/docs/handbook/generics.html , the latter will have a blog dedicated to resolve TtpeScript generics.

@ Tuples: declaration specifies each array element type array, and the array length can not exceed the number of elements specified variable declaration 
let arr: [string, number] = [ '1', 2];

If the assignment element beyond a defined length tuple position error occurs, the error will be two general operation (2493,2322): 2493 tips beyond the scope of tuples, 2322 prompt type non undefined type assignment, if an assignment undefined 2322 will not report the error. You can view detailed error official document: Document / project configuration / list of error messages

Thus for example, the following arr [3] forming a non undefined value:

arr[3] = 10;

TypeScript enumeration (enum) very friendly data structure provides a finite sequence set, it will default from zero to each element number, serial number can be obtained through the elements, you can also get the name of the element by number, however internal implementation uses a sacrificial way space for time, such as one element in the enumeration Color Blue, the underlying implementation is {Blue: 0,0: 'Blue'}, which achieved when the value of the corresponding element to find only need Color [0] can be acquired, and if the object or the front of the array in order to obtain a corresponding element of the object or can only be realized through the array.

1  // Enumeration 
2  enum {Color
 . 3      Red,
 . 4      Green,
 . 5      Blue
 . 6  }
 . 7 the console.log (Color.Red); // 0 
. 8  // custom number or value: number of values only, the character elements string 
. 9  enum {the Name
 10      Xiaoming =. 3 ,
 . 11      Xiaohong. 5 =
 12 is  }
 13 is the console.log (the Name [. 3]); // 'Xiaoming' 
14  // enumeration same can not be out of range, limited only find the enumeration set 
15 Color.YELLOW =. 4; // error (2339): Can not find 'Yellow' on the property type

1.3 Any type (any) with an invalid type (Void)

. 1  // A NY type: equivalent to JavaScript variable, depending on the type of the variable-type value, and may be arbitrarily changed 
2 the let notSure: = the any. 4 ;
 . 3 notSure = "Maybe INSTEAD A String" ;
 . 4 notSure = to false ;

There may be wondering Any variable type what's the use? It is not yet back to the JavaScript? Indeed, it can help us return to the type of JavaScript variable mode, which means that if we are doing the upgrade project, could not be identified in the type of variable we can use Any; there is data entered by the user or a third party library we may not be able to determine its type, this time we can solve these problems.

There is also a very critical application is an array TypeScript in front of the Array syntax If you need a different type of array elements we can use tuples to achieve, but there are constraints tuple index and the length, or may not complete some special needs, especially for the loose habits of JavaScript array mode, Any help TtypeScript achieve the same array of JavaScript:

let list: any[] = ['hello',100,true];

void type is not much use, it is used to indicate no type, its role is not used to describe the type, to a certain extent, it is the same with undefinde.

. 1  // void variable value is always undefined 
2 the let A: void = undefined;
 . 3  function foo (): void { // is used to indicate the function returns no value 
. 4      // return void ...; before we can represent functions no value is returned 
5      // javaScript wording does not check for errors before, need to look at the internal code reading function codes 
6 }

1.4 undefined、null

To false: The variable used to specify only the null and undefined value, null and undefined variables in TypeScript There is also a type of meaning, as they may be any subset of variables, of course, in the case of tsconfig.json "strictNullChecks" under.

1 let a:undefined = undefined;
2 let b:null = null;
3 let c: number = 10;
4 c = undefined;
5 c = null;
6 // tsconfig.json -- "strictNullChecks": false模式 

1.5 never: the type used to represent those values ​​will never exist. For example, throw an error, which usually occurs in error checking. Variables can also be a never type, but any variable assignment in addition to its own type of error will be prompted to type.

 1 interface Test {
 2     imgNumberPerWork: number
 3     displayCover: boolean
 4   }
 5   const test: Test = {
 6     imgNumberPerWork: 0,
 7     displayCover: true
 8   }
 9   function setValue (key: keyof Test, val: any) {
10     test[key] = val //Type 'any' is not assignable to type 'never'
11   }
12   setValue('imgNumberPerWork', 1)

Because Test.imgNumberPerWork example is a digital type, but any type of the value assigned in setValue (). Such a description, never any type of character class, can be assigned to any type of official document, but never in addition to their value can not be assigned any type.

never the type of reference scenarios are:

1  // 1. thrown 
2  function error (Message: String): {Never
 . 3      the throw  new new Error (Message);
 . 4  }
 . 5  // infinite loop 
. 6  function Loop (): {Never
 . 7      the while ( to true ) {}
 . 8  }
 . 9  // Never subset of all types, such as a subset of number: 
10  the let a: number;
 . 11 Y = (() => { the throw  new new Error 'Message'}) ();

1.6 Object (Object), object type (Type)

 About TypeScript of Object variable declarations:

. 1 the let the dataObject = {
 2    name: "Xiaoming" ,
 . 3    Age: 31 is
 . 4  }
 . 5  // error a 
. 6  // the dataObject = {} 
. 7  // error: type '{}' is missing the following properties from type '{ name: Tring; Age: Number;} ': name, Age TS 
. 8  //         type "{}" missing type "{name: tring; age: number;}" following attributes: name, Age TS 
. 9  
10  // error two 
. 11  // the dataObject = { 
12 is  //    A: 'STR' 
13 is  // } 
14  //Error: of the type '{A: Tring;}' IS not to the ASSIGNABLE of the type '{name: String; Age: Number The}' 
15  // Object literal May Known only the Specify the Properties, and 'A' does not exist in of the type '{ name: Tring; Age: Number} ' 
16  // type "{a: tring;}" can not be assigned to the type "{name: String; Age: Number}" 
. 17  // object field can only specify a known property type "{name: tring; age: number}" does not exist "a"

These two types of error messages are referred to '{name: string; age: number}', this means that the type of the variable type dataObject, only this type of name, age two fields, and these fields are designated string, number type, if you want to assign to dataObject object value must be in line with this type. Can not arbitrarily add fields, you can not delete fields, so the following written is wrong:

1  // error Three: missing fields 
2  // the dataObject = { 
. 3  //   name: 'Xiaohong' 
. 4  // }

In fact, a complete way of TypeScript in variable declarations of type Object is like this:

1 //声明TypeScript的Object对象
2 let dataObject:{name:string;age:number} = {
3   name: "xiaoming",
4   age: 31
5 }

Complex type declarations and type the keyword

1 let complex: {datas:number[]; myfunc:(item:number) => number[]} = {
2   datas:[1,2,3],
3   myfunc:function(item:number){
4     this.datas.push(item);
5     return this.datas;
6   }
7 }

If we need to declare multiple types of the same structure even more complex types, the best way is to type Object variable declaration and assignment separation, such as the above but also to the complex Object variable types, for example, the same structure multiple Object statement variable:

1  // defined by Object type keyword variable type 
2 type MyObject = {DATAS: Number []; myfunc: (Item: Number) => Number []};
 . 3  // declare a variable of type Object to a variable MyObject 
. 4 the let complex1 : the MyObject = {
 . 5    DATAS: [l, 2,3 ],
 . 6    myfunc: function (Item: Number) {
 . 7      the this .datas.push (Item);
 . 8      return  the this .datas;
 . 9    }
 10  }
 . 11 the let complex2: the MyObject = {
 12 is    DATAS: [1,2,3,5,6,7,8,9 ],
 13 is    myfunc: function(item:number){
14     this.datas.unshift(item);
15     return this.datas;
16   }
17 }

1.7 function type function

In front of the object variable type in the code has been TypeScript function declaration, function declaration keyword or function, but you need to specify the parameters and return types in the statement:

1 function add1(x:number,y:number):number{
2   return x+y;
3 }
4 
5 let add2 = function(x:number,y:number):number{
6   return x + y;
7 }

Another way function declaration, you can declare the function type, the mutator:

1 let myAdd : (baseValue: number, increment: number) => number = 
2 function(x:number,y:number) : number{
3   return x + y;
4 }

Function type parameter name and the name of the actual assignment of function parameters can be inconsistent, but the type and number of parameters must be consistent. About the void function return value (without any type) variable type mentioned at the time handling function does not return value, the function value is returned to void type:

1 let hintStamp(str:string):void{
2   console.log(str);
3 }

About TypeScript the type of function and more content here just shows the syntax of the statement, detailed attention to this blog :( To be added)

 

Guess you like

Origin www.cnblogs.com/ZheOneAndOnly/p/11762563.html