What is TypeScript
TypeScript is a free and open source programming language developed by Microsoft. It is a superset of JavaScript, and essentially adds optional static typing and class-based object-oriented programming to the language.
How TypeScript differs from JavaScript
TypeScript | JavaScript |
---|---|
Supersets of JavaScript are used to address the code complexity of large projects | A scripting language for creating dynamic web pages. |
Errors can be found and corrected at compile time | As an interpreted language, errors can only be found at run time |
Strongly typed, supporting both static and dynamic typing | Weak type, no static type option |
It is eventually compiled into JavaScript code that the browser can understand | It can be used directly in the browser |
Support for modules, generics, and interfaces | There is no support for modules, generics or interfaces |
Supports ES3, ES4, ES5, and ES6 | Compilation of other ES3, ES4, ES5 or ES6 features is not supported |
Community support is still growing, and it’s not great | Lots of community support and lots of documentation and problem-solving support |
TypeScript types
The base type
-
Common: Boolean, number, string, array, enum, any, void, unknown
-
Uncommon: tuple, NULL, undefine, never
Note: If we use any, we won’t be able to use the many protections TypeScript provides. By changing the any type to unknown, we have changed the default setting that allows all changes to prohibit any changes
Object type
The difference between interface and type: Type is more powerful, interface can be declared merge, type cannot.
An array type
interface IItem { id: number; name: string; isDad: boolean; } const objectArr: IItem[] = [{id: 1, name: 'isGod ', isGod: true}]; Const objectArr: Array<IItem> = [{id: 1, name: 'isGod ', isGod: true}]; const numberArr: number[] = [1, 2, 3]; const arr: (number | string)[] = [1, "string", 2];Copy the code
TypeScript interfaces
define
An interface is an important concept in object-oriented languages. It is an abstraction of behavior that needs to be implemented by classes. Interfaces in TypeScript are a very flexible concept. In addition to abstracting some of the behavior of a class, interfaces are often used to describe the Shape of an object.
interface Person { name: string; age? : number; } let Semlinker: Person = { name: "Semlinker", age: 33, };Copy the code
Interface inheritance
interface Animal{ eat():void; } interface Person extends Animal{ work():void; } class Web implements Person{ public name:string; constructor(name:string){ this.name = name } eat(){ console.log(this.name+'eat') } work(){ console.log(this.name+'work') }}Copy the code
The function interface
interface Person{ (name:string,age:number):string } var setData:Person = function(name:string,age:number):string{ return Name +age} setData(' zhang3 ', 18)Copy the code
TypeScript generics
define
A generic is a template that allows the same function to take different types of arguments. It is better to create reusable components using generics, which preserve parameter types, than using any (forgoing type checking). It addresses the reuse of classes, interfaces, methods, and support for indeterminable data types. Generics require that the parameters passed in be the same as those returned.
Function getData<T>(value:T):T{getData<T>(value:T):T{ } getData<number>(123)Copy the code
A generic interface
interface ConfigFn{ <T>(value:T):T; } var getData:ConfigFn=function<T>(value:T):T{return value} getData<string>Copy the code
Functions in TypeScript
function getInfo(name:string,age:number=20,... result:number[],sex? :string):string{ return `${name}----${age}----${sex}` }Copy the code
- Optional parameters must be configured to the last of the parameters, code warning, can be run
- The remaining arguments use three-point operators
Six, decoration
define
A decorator is a special type of declaration that can be attached to a class declaration, method, attribute, or parameter to modify the behavior of a class. A decorator is a method that can be injected into classes, methods, and property parameters to extend the functionality of classes, properties, methods, and parameters.
implementation
- Class decorator: declared before the class declaration (immediately following the class declaration). Class decorators are applied to class constructors and can be used to monitor, modify, or replace class definitions. Pass in a parameter. A class decorator expression is called at run time as a function, with the constructor of the class as its only argument. If the class decorator returns a value, it replaces the class declaration with the provided constructor.
- Property decorators: Pass in two arguments: static members are class constructors, and instance members are class prototype objects. Member name.
- Method decorators: Pass in three arguments: static members are class constructors, instance members are class prototype objects; Member name; Attribute descriptor for a member
- Method parameter decorator: Passes three arguments: static members are class constructors, instance members are class prototype objects; Parameter name; The index of a parameter in the function argument list
Function logClass1(params:string){return function(target:any){console.log(' class decorator 1')}} function LogClass2 (params:string){return function(target:any){console.log(' class decorator 2')}} function logAttribute(params? :string){return function(target:any,attrName:any){console.log(' attribute decorations ')}} function logMethod(params? : string) {return function (target: any, attrName: any desc: any) {the console. The log (' method decorators')}} function logParams1 (params? : string) {return function (target: any, attrName: any desc: any) {the console. The log (' method parameter decorator 1 ')}} function logParams2 (params? : string) {return function (target: any, attrName: any desc: any) {the console. The log (' method parameter decorator 2 ')}} @logClass1('http://www.baidu.com') @logClass2('xxx') class HttpClient{ @logAttribute() public apiUrl:string|undefined constructor{ } @logMethod() getData(){ return true } setData(@logParams1() attr1:any,@logParams2() attr2:any){ return true } } var http:any = new HttpClient();Copy the code
Decorator execution order
Properties > Method > Method Parameters > Class If there are more than one of the same decorators, it will execute the later one first
Seven,Pros and cons of TypeScript
Advantages:
- Readability and maintainability of code
- Most of the errors are found at compile time and many online bugs are avoided
- Enhancements to the editor and IDE include code completion, interface hints, jump to definition, refactoring, and more
Disadvantages:
- There is a cost to learning Interfaces, Generics, Classes, enumerated types, and other less familiar concepts
- Will increase some development costs, of course, this is early, later maintenance is easier
- Some JavaScript libraries require compatibility and provide declaration files, like VUe2, but the underlying compatibility for TS is not very good
- Ts compilation takes time, and as the project gets bigger, the speed at which the development environment can start up and the production environment can be packaged becomes a challenge