Why use Typescript?
Microsoft launched TypeScript with two goals in mind:
- Provide optional type systems for Javascript;
- Compatible with current and future JavaScript features.
Benefits of static typing:
- It facilitates code refactoring by catching errors as the compiler compiles.
- Clear type is good for reading.
Common JavaScript syntax
TypeScript is a “superset” of JavaScript that standardizes JavaScript syntax.
-
= = = = =
When using == for comparison, an implicit conversion is performed.
2= =2 true 2= ='2' true 2= = ='2' false Copy the code
-
reference
In addition to literals, any object in JavaScript (including functions, arrays, regular expressions, and so on) is a reference.
-
Null, and undefined
Variable not initialized: undefined. The variable is not available as NULL.
undefined= =undefined true undefined= =null true // Check if the variable is initialized if( typeofval ! = ='undefined') {}Copy the code
-
this
The this keyword points to the calling context
function foo(){console.log(this)} /** this --> window **/ var obj = {foo:function(){console.log(this)}} obj.foo() /** this --> obj */ Copy the code
-
closure
The inner function accesses the external variable, and the external function’s variable is bound by the inner function, called a closure.
function outer(){ var outerVal = '1' function inner(){ console.log(outerVal) } outer() } /** inner binds to outerVal */ Copy the code
-
digital
In JavaScript, the value is a 64-bit number with double precision
console.log(1. + 2.) / / 0.30000000000000004 Copy the code
Built-in integer type limit number. max_safe_INTEger-number.MIN_SAFE_INTEGER
Big.js is commonly used in financial calculations
NaN, returns NaN if the computed value is not a valid value, detects NaN, Number. IsNaN.
-
thuthy
!!!!! Double exclamation point, number one! Is to convert the value to a Boolean, the second logical inversion.
ES6 grammar
-
class
/*ES6*/ class Point { x: number y: number constructor(x: number, y: number) { this.x = x this.y = y } add(point: Point) { return new Point(this.x + point.x, this.y + point.y) } } /* Compiled ES5*/ var point = function(){ function Point(x, y){ this.x = x; this.y = y; } Point.prototype.add = function(point){ return new Point(this.x + point.x, this.y + point.y) } returnPoint; } ()Copy the code
inheritance
/*ES6*/ class Point3D extends Point { z: number constructor(x: number, y: number, z: number) { super(x, y) this.z = z } add(point: Point3D) { var point2D = super.add(point) return new Point3D(this.x + point2D.x, this.y + point2D.y, this.z + point.z) } } /* Compiled ES5*/ var point3D = function(_super){ __extends(Point3D, _super) function Point3D(x, y, z){ _super.call(this, x, y) this.z = z; } Point3D.prototype.add = function(point){ var point2D = _super.prototype.add.call(this, point) return new Point3D(this.x + point2D.x, this.y + point2D.y, this.z + point.z) } return Point; }(Point) /**__extends typescript generates */ when extends is compiled var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: []}instanceof Array && function (d, b) { d.__proto__ = b; }) | |function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; /* d represents the derived class, and b represents the base class */ return function (d, b) { extendStatics(d, b); // Copy static variables function __() { this.constructor = d; } // Keep the derived constructor d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new(4));//d.prototype.__proto__ = b.prototype}; }) ();Copy the code
__ proto __ prototype
All objects in javascript have the property __ proto __
Obj.property obj.__proto__.__proto__. Property **/ Copy the code
Javasript all functions have the property Prototype, which has a constructor pointing to the function itself.
function Foo(){ this.name = "xm" } var foo = new Foo(); /** Objects created from functions pass function prototype to __proto__*/ console.log(foo.__proto__ === Foo.prototype) Copy the code
-
Arrow function
var inc = x= > x + 1; Copy the code
The arrow function brings syntax brevity and this loss problems.
-
Rest parameters
. + represents the last parameter in the form of the parameter name, which is retrieved as an array.
-
Let and const
The var variable is the function scope and the let variable block scope
Var */ in the /** closure var funcs = [] for(var i = 0; i <3; i++){ funcs.push(function(){ console.log(i) }) } for(var j = 0; j <3; j++){ funcs[j](); } 3 * / / * output Copy the code
Const declares a constant value.
-
deconstruction
Object and array destructions are supported.
/* Object destruct */ var person = {name:'x'.age:12.gender:1} var {name, age} = person console.log(name, age) // x, 12 var{x, y, ... remaining} = {x: 1.y: 2.z: 4.w: 5} // delete x,y console.log(x,y,remaining) / / 1, 2, {5} z: 4, w: Copy the code
-
Extended operator
Function.prototype.apply
Call * / / * the apply function foo(x,y){} var args = [0.1] foo.apply(null, args) / / new syntaxfoo(... args)// Append the element to the array var list = [1.2] list = [...list, 3] / / [1, 2, 3] list = [0. list,4] / /,1,2,3,4 [0] Copy the code
-
for… of
/*for... in*/ for(var e in [7.8.9]) {console.log(e) }// return index for(var e of [7.8.9]) {console.log(e) }// Return the element Copy the code
-
Promise
Use Promise to handle asynchrony and callback functions.
var promise = new Promise((resolve, reject) = > {resolve()// Callback the correct value reject() / / the outliers }) promise.then(res= > {}) / / normal .catch(err= > {}) / / exception Copy the code
All ([promise1,promise2]). Then (res => [result1, result2])
-
generators
function* idGen(){ let index = 0 while(index < 3) yield / * * / index++; } var id = idGen(); console.log(id.next()); console.log(id.next()); console.log(id.next()); console.log(id.next()); Copy the code
-
async/await
async function foo(){
var result = await exPromise() // Wait for the promise implementation to return
console.log(result)
}
Copy the code
TS Project Composition
-
Compilation context
Tsconfig. json configuration file. Configuration option: tsconfig
-
The statement space
Type declaration space and variable declaration space.
- Class (class): type.value.
- Interface (interface): type.
- Enumeration (enum): type.value.
- Category name (type): type.
- Function (function): value.
- Variables (let, const, var, parameters): value.
-
The module
By default, declarations are in the global namespace. Use export to become a file module.
Module path lookup
/** Relative path **/ import * as foo from './foo' // Peer directory import * as foo from '.. /foo' // Upper directory import * as foo from '.. /someFolder/foo // relative directory /** Import * as foo from 'foo'/* Find the order./node_modules/foo.. /node_modules/foo .. /.. /node_modules/foo */ import * as foo from 'something/foo' /** ./node_modules/something/foo .. /node_modules/something/foo .. /.. /node_modules/something/foo */ /* place */ import * as foo from 'fooTs foo is a directory foo/index.ts foo is a directory foo/package.json has types foo is a directory foo/package.json has main **/Copy the code
-
The namespace
/ / typescript statement namespace Utility { export function log(msg) { console.log(msg); } export function error(msg) { console.log(msg); }}// usage Utility.log('Call me'); Utility.error('maybe'); Copy the code
var Utility; (function (Utility) { function log(msg) { console.log(msg); } Utility.log = log; function error(msg) { console.log(msg); } Utility.error = error; })(Utility || (Utility = {})); // usage Utility.log('Call me'); Utility.error('maybe'); Copy the code
-
Dynamically imported expression
// Dynamic loading import(/* webpackChunkName: "momentjs" */ 'moment') .then(moment= > { // Lazy modules have all types and work on schedule const time = moment().format(); console.log('TypeScript >= 2.4.0 Dynamic Import Expression:'); console.log(time); }) .catch(err= > { console.log('Failed to load moment', err); }); Copy the code
Creating a TS Project
- Install the Node environment, create a directory and run NPM init -y.
- Ts NPM install typescript –save-dev;
- Node.d.ntpm install @types/node –save-dev;
- Json NPX TSC –init –rootDir SRC –outDir lib –esModuleInterop –resolveJsonModule –lib es6, dom –module commonjs;
- NPM install ts-node –save-dev to compile and run in real-time;
- Add nodemon: NPM install nodemon –save-dev, it will call TS-Node whenever the file is changed.
TS type system
-
The basic concept
Basic type Number String Boolean String []
Interface interface
Special types any, null, undefined, and void
/ / interface interface Name{ first: string.last: string }; let n : Name; n = { first: 'Li'.last:'p' } / / generics function contact<T> (items : T[]) :T[]{ / /... return items; } // Union type function join(items : string[] | string){ / /... } // Cross types function extend<T.U> (first: T, last : U) :T & U{ const result = <T & U>{} return result} / / tuple type let nameNum: [string, number] / / type alias type mind = string | number let m: mindCopy the code
-
@types
The repository @types controls global compileroptions. types by configuring tsconfig.json to compileroptions. types.
-
Environmental statement
Declare with keyword declare, usually in a. D. ts file.
-
The enumeration
Numeric enumeration and string enumeration.
-
lib.d.ts
When TypeScript is installed, a lib.d.ts declaration file is installed along with it. This file contains various common JavaScript environment declarations found in the JavaScript runtime and DOM (Document Object Model).
-
function
Type inc = (num: number) => number
-
Callable and instantiable
/ / to call
interface ReturnStr{
() : string;
}
declare const foo : ReturnStr
const str = foo() // STR string
// Inline comments
const overload: {
(foo: string) :string;
(foo: number) :number;
} = (foo: any) = > foo
// instantiable
interface NewAble {
new() :string;
}
declare const newAble: NewAble;
const foo = new newAble
Copy the code
-
Types of assertions
Ts can override the types it inferences and analyzes in any way, called type assertions.
interface Foo{ Bar : string } const f1 = {} as Foo; f1.bar = "1"; const f2 = <Foo>{}; f2.bar = "2"; Copy the code
-
Freshness
Check literal types
function hasName(some: { name: string }) { some.name = "name"; / / right some.age = 12; / / error } Copy the code
-
Type of protection
Typeof (typeof x === ‘string’)
instanceof (foo instanceof Foo)
In Checks whether an object has an attribute
-
readonly
type Foo = { readonly bar: string; }; const f: Foo = { bar: "x" }; f.bar = "y"; // Error, unmodifiable Copy the code
-
The generic
Constraints between instance members of a class, class methods, function parameters, and function return values.
-
never
The never type is the bottom type in TypeScript. For a function that always throws an error or a function that always throws an error.
Void denotes no type and never denotes the type of a value that never exists.
-
Exception handling
try { throw new Error("err."); } catch (error) { console.log(error) } Copy the code
Code style conventions
-
Name variables and functions using the camelCase form.
-
Name the class using the PascalCase form.
-
Name the interface using the PascalCase format.
-
Type aliases are named in PascalCase form.
-
Namespaces are named using the PascalCase form.
-
Enumeration types are named using the PascalCase form.
-
Null and undefined are not recommended when you need to explicitly indicate that they are not available.
-
formatting
Format the TSFMT command with single quotation marks and TAB Spaces. Interface is recommended if extends or implements is used.
TS Compilation Principle
. To be continued to look