A list,
- TypeScript is a superset of JavaScript that supports the ECMAScript 6 standard.
- TypeScript a free and open source programming language developed by Microsoft.
- TypeScript is designed for large applications that can be compiled into pure JavaScript that runs in any browser.
- TypeScript extends JavaScript’s syntax so that existing JavaScript code can work with TypeScript without modification, and TypeScript provides compile-time static type checking through type annotations. TypeScript processes existing JavaScript code and only compiles TypeScript code within it
Having said that, typescript is a superset of javascript. However, we also learn from Typecript that typescript makes code more maintainable and less bugable by introducing a static typing system while preserving JavaScript runtime behavior intact.
Second, the main content
- Now I use mind maps to map the main typescript content.
Three,
- 1. Type system
Because that’s one thing about typescript: types. It has more type constraints than javascript. The purpose of doing this is to check the code before it runs and ensure the quality and maintainability of the code.
- 2. Static type
JavaScript is dynamically typed, because syntax is checked at runtime, and if there is an error, it gets stuck at the current error, preventing the following code from running. Typescript, on the other hand, starts checking syntax at compile time and notifies errors immediately. That’s static typing.
- 3. Weak types
We know that JavaScript is weakly typed, but typescript is fully compatible with JavaScript. It does not modify the features of the JavaScript runtime. So it’s a weak type.
- 4. Core design concept
The introduction of a static type system improves the maintainability of code and reduces possible bugs while preserving JavaScript runtime behavior in its entirety.
- 5, installation
NPM install -g typescript or YARN add -g typescript // Check whether installation is successful: tsc-vCopy the code
- The first typescript program
This is because TypeScript only statically checks types at compile time, and if errors are found, an error is reported at compile time. At run time, like normal JavaScript files, there is no type checking.
However, TypeScript compiles with errors and generates compilation results, and we can still see compiled JS files with no syntax errors. This can print the corresponding JS file, you can verify.
- 7. For running typescript code (without webpack, etc.), see vscode running typescript
Four, basic
-
1. Raw data type
- boolean
Let isOk: Boolean = false let isFine: Boolean = new Boolean(0) The constructor Boolean creates an object that is not a Boolean. // New Boolean() returns an objectCopy the code
- number
Let n1:number = 123 let n2:number = NaNCopy the code
- string
Let name:string = 'zhangsan' let age:string = 24 // Compile name pass, but in age, not pass. Var name = 'zhangsan' var age = 24 in Hello typescriptCopy the code
- Null, and undefined
Null and undefined define primitive data types in typescript. That is, undefined and NULL are subtypes of all types.
Let a1:undefined = undefined let a2:null = null Let str1:string = undefined // Compiler passed let num1:number = null // Compiler passedCopy the code
- In typescript, void represents an empty value and does not return any type
Let n:void let num:number = n Void {console.log('hello world')} function people():void{console.log('hello world')}Copy the code
-
2, any value
- In typescript, any represents any value type. When a variable is declared, it does not declare a type and defaults to any
Let p:any = 'zhangsan' let n:any = 123 n = '123' let a:any = [] let b=true Var p =' zhangsan' var n= 123 n='123' var a =[] var b = true // If, is a common type, changing the type during assignment is not allowed.Copy the code
-
3. Type inference
- If a type is not explicitly specified at declaration time, typescript infers a type according to the rules of type inference.
Error TS2322: Type 'number' is not assignable to Type 'string'.Copy the code
Type corollary, the result is:
Let a:string = 'lisi' a = 20Copy the code
However, if no value is assigned at the time of definition: is inferred to be of type any and is not type checked at all
let b; B ='wangwu' b=20Copy the code
-
4. Union types
- When declaring a type, you can declare more than one. Separated with |
Let somethings: string | number somethings = 'ABCD' somethings = 24 / / compile successfully, Var somethings somethings= 'ABCD' somethings= 24Copy the code
However, when assigning, it does not belong to the declared type:
Let somethings: string | number somethings = 'ABCD' somethings = false / / compile error, but compile results (right) : var somethings somethings= 'ABCD' somethings = falseCopy the code
At this point, an error will be reported:
- Methods for joining types:
The function setting (attrs: string | number) : number {return math.h ceil (attrs)} / / an errorCopy the code
At this point, compilations will also fail: math.ceil is not a common attribute of string and number
- Attributes of the union type:
Let p1: string | number p1 = 'zhangsan'. The console log (p1) length) / / 8 p1 = 20. The console log (p1) length) / / compile error because / / type "Number" does not have attribute "length"Copy the code
Type “number” does not have attribute “length”
Therefore, when accessing properties or methods of a union type, it is important to consider the common properties of the type so that compilation errors do not occur.
-
5, interface
- Interfaces are one of the most useful tools in an object-oriented JavaScript programmer’s toolbox
- There are three main ways to mimic an interface in JavaScript: through annotations, property checking, and duck sorting (you can view your own web data), and a combination of these three can produce an interface like effect.
- This interface is not what we call a front – and – back – end interface.
- In typescript, interfaces are used to define the type of an object.
Here’s a simple example:
interface Dog{ name:string; color:string; Age :number} let xiaohei:Dog = {name:' xiaohei ', color:'black', age:2}Copy the code
Use interface to define an interface for Dog, and define a variable xiaohei, which is of type Dog.
-
An interface defines attributes or methods. When constraining variables, the interface must define all attributes of the interface.
When some attributes are missing:
interface Animal{ name:string; eat(str:string):void } class Dog implements Animal{ name:string; // console.log(this.log){// console.log(this.log){// console.log(this.log){// console.log(this.log){// console.log(this.log){console.log(this.log){console.log(this.log){console.log(this.log){console.log(this.log){console.log(this.log){console.log(this.log); D. eat(); // Error: eat(); // error: eat()Copy the code
At this time, the compilation error:
When there are more attributes:
interface Dog{ name:string; color:string; } let xiaohei:Dog = {name:' xiaohei ', color:'black', age:2} The compilation will also report an errorCopy the code
At this time, the compilation error:
-
6. Optional properties
At this point, we wondered if we could define the attributes of the interface without matching exactly.
The answer is:?
interface Dog1{ name:string; color:string; age? :number; } let xiaohei:Dog1 = {name:' xiaohei ', color:'black'} So you can see, in this case, the keyword, right? Can solve the imperfect match. That is, optional propertiesCopy the code
- 7. Arbitrary attributes
We want to define an unknown property. However, we do not know the name of this attribute, is it supported?
The answer is unknownName. UnknownName is an unknown attribute name and can be defined by unknownName.
interface Student{ name:string; age:number; [unknownName:string]:any; } let zhangsan:Student = {name:'zs', age:10, classNo:20, school:'一 zhong 'Copy the code
When we put [unknownName:string]:string. At this time:
interface Student{ name:string; age:number; [unknownName:string]:string; } let zhangsan:Student = { name:'zs', age:10, classNo:20, // Can't assign type "number" to type "string index "// can't assign type "number" to type "string"Copy the code
As you can see, once any attribute is defined, the type of the determined attribute and the optional attribute must be a subset of its type.
Thus, we can combine the union properties:
interface Student{ name:string; age? :number; [unknownName: string] : string | number} let zhangsan: Student = {name: 'zs, classNo: 20, school:' 1 '} / / compile successfullyCopy the code
- 8. Read-only property
In a javascirpt form, we might not want someone else to modify the form’s data, so we can set read-only properties.
In typescript, read-only properties also exist.
interface Student{ readonly name:string; age? :number; [unknownName:string]:string|number } let zhangsan:Student = { name:'zs', classNo:20, } zhangsan.name ='lisi' school:' 1 '} zhangsan.name ='lisi' school:' 1 '} zhangsan.name ='lisiCopy the code
Note: When Student name is set to readonly, name must be present when zhangsan is defined.
-
9. The type of array
- Notation 1 :([type + square brackets])
Let arr: number [] = [1, 2, 3, 4, 5] / / compile successfully let arr1: number [] = [' 1 ', 2, 5-tetrafluorobenzoic] / / compile error: We can't assign type "string" to type "number" because: arr1 is number, so every item in the array must be number arr. Push ('zs') An argument of type "string" cannot be assigned to an argument of type "number" // this is because the string 'ZS' is added to the ARR array so that each item must not be a numberCopy the code
- Notation 2 :(generic)
Let a:Array<number> =[1,2,3,4,5] // see the next section for Array genericsCopy the code
- Representation three :(interface representation)
Interface Student{[index:number]:string} let ZS :Student =['name','age','classno'Copy the code
- Any is applied to the array
Let arr:any[] = ['zs',12,' sz ']Copy the code
-
10. Type of function
(1) In typescript, functions are also represented in two ways: anonymous functions and function declarations
Function a():string{return 'c'} var f = function():number{return 123}Copy the code
(2) Define method pass parameters in typescript
function sum(x:number,y:number):number{ return x+y } var fsum2= function(x:number,y:number):number{ return x+y } Copy the code
(3) In typescript, optional arguments to methods
// In es5, the arguments and parameters of methods can be different. Function getInfo(name:string,age?) function getInfo(name:string,age? : number) : string {the if (age) {return ` ${name} - ${age} `} else {return ` ${name} - age secret `}} console.log(getInfo('zhangsan',123)) console.log(getInfo('lisi'))Copy the code
(4) In typescript, the default argument to a method
Function sum(a:number,b:number=20):number{return a+b} alert(sum(10)) //30 alert(sum(10,10)) // 20Copy the code
(5) In typescript, the residual argument method
// The three-point operator accepts the value passed by the parameter. result:number[]):number{ var sum = 0; for(var i=0; i<result.length; I++) + = {the sum result [I]} return sum} alert (sum (1, 2, 3, 4)) / / 10Copy the code
(6) In typescript, functions are overloaded
Method overloading in Java: Function overloading occurs when two or more functions of the same name are overloaded, but their arguments are different.
Overloading in typescript: The purpose of multiple functions by providing multiple function type definitions for the same function
Function sum(a,b){console.log(' 1111')} function sum(a,b){console.log(' 1111')}Copy the code
The typescript overloading
function getInfo(name:string):string; function getInfo(age:number):string; Function getInfo(STR :any):any{if(typeof STR ==='string') else{return 'age '+ age}} function getInfo(STR :any):any{if(typeof STR ==='string') else{return' age '+ age}} Alert (getInfo(true)) alert(getInfo(true)) alert(getInfo(true)Copy the code
- Types of assertions
Basically, you make an assumption that the compile will pass. Type assertion is more like a type choice than a cast.
As is recommended, as is only supported in syntaxes such as JSX.
function func(val: string | number): Number {if (val.length) {return val.length} else {return val.toString().length}} // Compilation errorCopy the code
Because when accessing an attribute of a union type value, the attribute must be common to all possible types, length is not common, and the type of val is not determined at this point, so the compilation fails.
When we use type assertion:
function func(val:string|number):number{ if((val as string).length){ return (val as string).length }else{ return Val.tostring ().length}} // compile successfully // declare val toStringCopy the code
Type assertions are purely a compile-time syntax and a way to give the compiler information on how to analyze code.
Double assertion
- Any type can be asserted to be any
- Any can be asserted to any type
function handler(event:Event){ const mouseEvent = event as MouseEvent } Copy the code
However, the following example
Function handler(event: event){const mouseEvent = event as HTMLElement} None of them can be assigned to the otherCopy the code
If you continue to use that type, you can use double assertions
Any is compatible with all types of fried rice cake.
function handler(event:Event){ const element =(event as any) as HTMLElement // ok } Copy the code
End of the five,
That’s all for the notes on the basics. Next, we’ll start with typescript advanced content.
I often see my friends around me, always say, new technology, and iteration, and the whole work, really can’t learn, can’t do… Meybe is not learning in the right way and mentality.
Practice, read, practice. Slow progress, quantitative change can induce qualitative change. Put a good attitude, refueling!