Introduce Typescript
- Typescript is an open source programming language developed by Microsoft
- Typescript is a superset of Javascript that follows the latest ES6 and ES5 specifications. Typescript extends Javascript’s syntax.
Typescript installs and compiles
Installation: Node.js must be installed before using the NPM command
NPM i-g typescript or CNPM i-g typescript NPM install - g ` CNPM - registry=https://registry.npm.taobao.org) or yarm global add typescriptCopy the code
Check whether the installation is successful:
tsc -v
Copy the code
Run:
tsc helloworld.ts
Copy the code
Compile the TS code into ES5 code and run it
Typescript development tools Vscode automatically compiles. Ts files
- through
tsc --init
Create the tsconfig.json configuration file
2. Run the ts 3. When you save it again, ts will be automatically compiled into JS to run
Data types in Tpescript
Variables defined in typescript must be typed
Boolean type (Boolean)
True and false
let flag:bollean = true;
Copy the code
Number type
let a:number = 123;
Copy the code
String type (string)
let str:string = 'world';
Copy the code
Array type (array)
let hobby:string[] = [ukulele."Sir"];
let hobby:Array<string> = [ukulele."Sir"];
Copy the code
Tuple Type
Note: Is a type of array. You can specify the data type of each item in the array.
let arr:[string, number, boolean] = ["Life", 123, true];
Copy the code
Enumeration Type (enum)
Often used to identify status
Enum Enumeration name {identifier [= integer constant], identifier [= integer constant],... Identifier [= integer constant]}; Pay_status 0: no payment is made. 1: payment is made. 2: transaction is successfultrue0 meansfalse
enum Flag {
success = 1,
error = 0
}
letf:Flag = Flag.success; console.log(f); // Print out 1Copy the code
Any type (any)
let flag:any=true;
flag = 123;
Copy the code
Null, and undefined
Is a subtype of another data type (never)
letflag:undefined; console.log(flag); Note: An element may be of type number, undefined or nullletflag2:undefined | number; flag = 123; console.log(flag2); Printout 123Copy the code
Void type
Typescript means that there is no type at all, which is typically used to define methods that return no value. Es5:
function run() {
console.log(1);
}
run();
Copy the code
In typescript :(indicates that no type is returned)
function run():void {
console.log(1);
}
run();
Copy the code
Never type
Subtypes of other types, including null and undefined, that represent values that never occur. Variables of life never can only be assigned by type never.
let a:null;
a = null; // A can only be null
let b:undefined;
b = undefined; // b can only be undefined
Copy the code
Functions in Typescript
Function declaration:
-
Methods for defining functions in ES5
function run() { return 'run1' } // Anonymous function var run2 = function() { return 'run2' } Copy the code
-
Methods for defining functions in typescript
Js function run():string {return ‘run1’}
Var run2 = function():string {return 'run2'} ' 'Copy the code
-
Typescript defines method pass-throughs
function getInfo(name: string, age: number) :string { return `${name}This year,${age}At the age of `; } // Anonymous function var getInfo = function(name: string, age: number) :string { return `${name}This year,${age}At the age of `; } // A function with no return value function run() :void { console.log('123'); } Copy the code
-
Method This parameter is optional
In ES5, method arguments and parameters can be different, but in TS, parameters and parameters must be the same. If they are different, you need to configure optional parameters.
The argument passed is followed by '? Function getInfo(age?); function getInfo(age?); : number,name: string):string ```js function getInfo(name: string, age? : number):string {if (age) {return '${name} year ${age} age'; } else {return '${name}'; }} ` ` `Copy the code
- The default parameters
Function getInfo(name: string, age: string) function getInfo(name: string, age: string) Number = 20):string {if (age) {return ‘${name}’ ${age} ‘; } else {return ‘${name}’; Js function sum(a: number, b: number, c: number):string {return a + b + c; }
function sum(... result:number[]):string { let sum = 0; for(let i = 0; i < result.length; i++) { sum += result[i]; } return sum; } alert(sum(1, 2, 3)) ```Copy the code
- Reloading of functions in Java: An overload is when two or more functions of the same name are overloaded, but their arguments are different. Overloading in typescript: The purpose of experimenting with multiple functions by providing multiple function type definitions for the same function.
function sun(config) {}function sun(config, value) {}// A method with the same name appears in ES5. The following method replaces the above method Copy the code
// The same function passes different parameters to achieve different functions function sun(name: string) :string; function sun(sex: boolean) :boolean; function sun(str: any) :any{ if (typeOf str === 'string') { return name; } else { return str; } } alert(sun('Joe')); Copy the code
- Arrow function, es6
setTimeout(function() { alert('run'); }, 1000) // This in the arrow function points to the context setTimeout(() = > { alert('run'); }, 1000) Copy the code
Class in the typescript
Inheritance in ES5
-
Es5 classes in the
function Person() { this.name = 'Joe'; this.age = 28; } var person = new Person(); alert(person.name); Copy the code
-
Methods added to the constructor and prototype chain
function Person() { this.name = 'Joe'; / / property this.age = 28; this.run = function() { alert(this.name); }}// Extend the attributes above the prototype chain // Attributes above the stereotype chain are shared by multiple instances Person.propotype.sex = "Male"; Person.propotype.work = function() { alert(this.name); } // The method that is instantiated with the new keyword is called instance method, and p.bark () is instance method var person = new Person(); p.work(); ` `` Copy the code
-
A static method in a class
Person.getInfo = function() { alert('I'm a static method'); } // Call static methods Person.getInfo(); Copy the code
-
In es5, the inherited class can only inherit properties and methods in the constructor through the combination inheritance method of stereotype chain + object impersonation
function web() { Person.call(this); } var w = new web(); w.run(); // Object impersonation can inherit properties and methods from constructors w.work(); // An error is reported. The object can inherit properties and methods from the constructor, but cannot inherit properties and methods from the prototype chain Copy the code
It can inherit properties and methods in the constructor. It can also inherit methods on the chain. Disadvantages: there is no way to pass arguments to the parent class when instantiating a word class
web.prototype = new Person(); // The prototype chain implements inheritance var w = new web(); w.run(); Copy the code
Composite inheritance of prototype chain + object impersonation
function Person(name, age) { this.name = this.name; this.age = this.age; this.run = function() { alert(this.name); }}Copy the code
The first:
function web(name, age) { Person.call(this, name, age); } web.prototype = new Person(); var w = new web("Zhang".20); w.run(); Copy the code
The second:
web.prototype = Person.propotype; Copy the code
Methods that define classes in TS
class
Classes defined in ES5:
function Person(name) {
this.name = name;
this.run = function() {
alert(this.name)
}
}
var p = new Person('Joe');
p.run();
Copy the code
class Person {
name: string; / / property
constructor(n: string) { The constructor is triggered when the constructor instantiates the class
this.name = n;
}
run(): void {
alert(this.name); }}var p = new Person('Joe');
p.run();
Copy the code
inheritance
The method of the parent class and the method of the child class are the same, call the method of the child class, first take the method of the child class, if the child class does not have a method to look in the parent class
class Person{
name: string;
constructor(name: string) {
this.name = name;
}
run(): void {
return `The ${this.name}It's time for bed}}var p = new Person('HerayChen');
alert(p.run());
class Child extends Person {
constructor(name: string) {
// super means to call the parent constructor
super(name); }}var c= new Child('Joe');
alert(c.run();)
Copy the code
The modifier
Class modifiers typescript provides us with three types of modifiers when defining properties. Property, without modifier, is public by default.
- Public: public, accessible inside, outside, and in subclasses of the current class
- Private: private, accessible within the current class
- Protected: The protection type, accessible in the current class or subclass
Static properties, static methods
Static methods in ES5:
function Person() {
this.run1 = function() {}}// Static method
Person.run2 = function() {}// Static attributes
Person.name = 'haha';
var p = new Person();
Person.run2(); // Static method calls
Copy the code
Static methods in typescript:
class Person {
public name: string;
// Static attributes
static sex: "Male";
constructor(name: string) {
this.name = name;
}
// Instance method
run() {
alert(Name of `The ${this.name }`);
}
// Static method
// Note: static methods can only call static properties
static work() {
alert(Small `${ Person.sex }The child is at work)}}// Call the instance method
var p = new Person('Joe');
p.run();
// Call static methods
Person.work();
// Invoke static properties
alert(Person.sex);
Copy the code
polymorphism
What is polymorphism?
A parent class defines a method that is not implemented and lets its subclasses implement it, each of which behaves differently. Polymorphism is also a manifestation of inheritance. Polymorphism belongs to inheritance.Copy the code
class Person {
name: string;
constructor(name: string) {
this.name = name
}
eat() {
console.log("What's for today?")}}class Menu extends Person {
constructor(name: string) {
// Inherit the attributes and methods of the parent class
super(a); }eat() {
return this.name + 'Noodles today'; }}Copy the code
Abstract classes, abstract methods
Abstract classes in typescript are base classes that provide inheritance from other classes and cannot be instantiated directly.
The abstract keyword is used to define abstract classes and methods. Abstract methods in abstract classes do not contain concrete implementations and must be implemented in derived classes.
Abstract methods can only be placed in abstract classes.
Abstract classes and abstract methods are used to define standards.
Subclasses of the Person class must contain the eat method:
abstract class Person {
public name: string;
constructor(name: string) {
this.name = name;
}
// His subclass must have the eat methodAbstract the eat () : any; } ~ ~var p = newPerson(); ~ ~// Abstract classes cannot be instantiated directly
class Menu extends Person {
// Subclasses of the abstract class must implement the abstract methods in the abstract class
constructor(name: any) {
super(a); }eat() {
console.log(`The ${this.name}`)}}// Call the abstract method
var m = new Menu('Little boy');
m.eat();
Copy the code
Interfaces in typescript
Functions of interfaces: In object-oriented programming, the interface is a standard definition, specification, which defines the behavior and action in the program design, interface have played an important role in a limit and specifications, interface defines a number of classes need to follow the specifications, interface does not care about these classes the internal state of the data, also don’t care about the class methods of the implementation details, Instead, classes that provide these methods can be used as they should be. Typescript interfaces are similar to Java, with more flexible interface types, including properties, functions, indexable classes, and so on.
The attribute interface
Constraints on JSON:
// define methods in ts,
// 1. Pass the parameter and specify the data type to pass the parameter
function printlabel(label: string) :void {
console.log('printlabel');
}
printlabel('haha');
// 2. Ts custom sends json constraints when passing parameters
function printlabel(labelInfo{ lable: string }) :void {
console.log('printlabel');
}
~~printlabel('haha'); ~ ~// Error
printlabel({ lable: 'Joe' }); // Write it correctly
// 3. Restrict the batch method passing parameters
// Specification of interfaces, behaviors, and actions that constrain batch methods
// the interface keyword defines methods (constraints on incoming objects, attribute constraints)
interface FullName {
firstName: string; // Notice the semicolon ending
secondName: string;
}
function printName(name: FullName) {
The firstName secondName object must be passed
console.log('firstName' + name.firstName + ' ' + name.secondName);
}
var obj = {
age: 20.firstName: 'Joe'.secondName: 'zhang'
}
printName(obj);
Copy the code
Optional attribute interface:
interface FullName {
firstName: string; // Notice the semicolon ending
// Define interface attribute names followed by? Then, prove that this parameter can be passed or notsecondName? : string; }function getName(name: FullName) {
console.log(name);
}
// The order of arguments can be different
getName({
firstName: '张'.secondName: '三'
});
Copy the code
Test drive (encapsulating Ajax requests through attribute interfaces) :
interface Config {
type: string; url: string; data? : string; dataType: string; }function ajax(config: Config) {
var xhr = new XMLHttpRequest();
xhr.open(config.url, config.url, "true");
xhr.send(config.data);
xhr.oreadystatechange = function() {
if(xhr.readyState == 4 && xhr.state == 200) {
console.log("Data request successful");
if (config.dataType == 'json') {
JSON.parse(xhr.responseText)
} else {
console.log(xhr.responseText);
}
}
}
}
ajax({
type: 'get'.url: 'http://www.baidu.com'.dataType: 'json'
})
Copy the code
Function type interface (batch constraint)
Function type interface: method parameters passed in, and return values are constrained. Encrypted function type interface
interface encrypt {
(key: string, value: string): string;
}
var md: encrypt = function(key: string, value: string) :string {
// simulate the operation
return key + value;
}
console.log(md('name'.'Joe'));
Copy the code
Indexable interface
Indexable interfaces: arrays, object constraints (uncommon)
// Constraints on arrays
interface UerArr {
[index: number]: string
}
var arr: UerArr = ['11'.'22'.'33'.'44'.'55'];
console.log(arr[0]);
// Constraints on objects
interface UserObj {
[index: string]: string
}
var obj: UserObj = {name: 'Joe'};
console.log(obj);
Copy the code
Class type interface
Class type interface: Constraints on classes.
// Constraints on classes are somewhat similar to those on abstract classes
interface typeGroup {
name: string,
hobby(str: string): void;
}
class uerInfo implements typeGroup {
name: string,
construcor(name: string) {
this.name = name;
}
hobby() {
console.log(this.name); }}var h = new typeGroup('zhang'); // Print zhang
Copy the code
The interface extension
Interface extension: An interface can inherit from an interface.
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)
}
work() {
console.log(this.name)
}
}
var w = new web('xiao');
w.work(); // 打印输出 xiao
Copy the code
Generics in typescript
The definition of generics
Generics: In software engineering, we need to not only create consistent, well-defined apis, but also consider reusability. The ability of components to support not only current data types but also future data types gives you a lot of flexibility when building large systems.
In languages like C# and Java, generic classes can be used to create reusable components that can support multiple types of data. This allows users to use components in their own data types.
Generics address the reuse of classes, interfaces, methods, and support for non-specific data types.
Generic function
// Only string data is returned
function getData(value: string) :string {
return value;
}
// Both string and number are mandatory
// Using any abandons type checking
function getData(vakue: any) :any {
return value;
}
// Generics: can support non-specific data types (requirement: the parameters passed are the same as those returned)
// T stands for generics. What type is determined when this method is called
function getData<T> (vakue: T) :T {
return value;
}
getData<number>(123);
Copy the code
A generic class
Class generics (what type of argument is passed in, what type of argument is returned) :
Minimum heap algorithm, need to support both the return number and string types, through the generic implementation.
Generic classes
class MinClass {
public list:number[] = [];
add(num: number) {
this.list.push(num);
}
min(): num {
var minNum = this.list[0];
for(var i = 0; i < this.list.length; i++) {
if(minNum > this.list[i]) {
minNum = this.list[i]; }}returnminNum; }}var m =new MinClass();
m.add(3);
m.add(4);
m.add(5);
m.add(6);
alert(m.min());
Copy the code
Generic class supersets
class MinClass<T> {
public list: T[] = [];
add(num: T) {
this.list.push(num);
}
min(): T {
var minNum = this.list[0];
for(var i = 0; i < this.list.length; i++) {
if(minNum > this.list[i]) {
minNum = this.list[i]; }}returnminNum; }}// Instantiate the class and specify the data type to return
var m1 = new MinClass<number>();
m1.add(3);
m1.add(4);
m1.add(5);
m1.add(6);
alert(m.min());
Copy the code
Generic classes that take classes as parameter types
Define a User class that maps database fields, define a MySql class that manipulates the database, and pass the User class as a parameter to MySqlDb.
class User {
username: string | undefined;
password: string | undefined;
}
class MySqlDb {
add(user: User): boolean {
console.log(user);
return true; }}var u = new User();
u.username = "Zhang";
u.password = 123;
var d = newMySqlDb(); d.add(u); -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- division -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --// Operate on database generics
class MySqlDb<T> {
add(userInfo: T): boolean {
console.log(user);
return true; }}// Define a User class to map to the database
class User {
username: string | undefined;
password: string | undefined;
}
var u = new User();
u.username = "Zhang";
u.password = 123;
var d = new MySqlDb<User>();
d.add(u);
Copy the code
A generic interface
// Interface of function type
interface ConfigFun {
(value1: string, value2: string): string;
}
var setData: ConfigFun = function(value: string,value2: string) :string {
return value1 + value2;
}
setData('n'.'3');
// Generic interface
// 1. The first way to define generic interfaces
interface ConfigFun {
<T>(value: T): T;
}
var setData: ConfigFun = function(value: T,value2: T) :T{
return value1 + value2;
}
setData<string>('n'.'3');
// 2. The second way to define generic interfaces
interface ConfigFun<T> {
(value: T): T;
}
function setData<T> (value: T) :T{
return value1;
}
var mySetData: ConfigFun<string> = setData;
mySetData('N3');
Copy the code
Integration of typescript types, interfaces, and generics -typescript encapsulates the underlying libraries that operate Mysql Mongodb Mssql
Function: define an operation database library is Mysql Mssql Mongodb
Requirements: the Mysql MsSql MongoDb function has the same add update delete GET method
Note: Uniform specification constraints, and code reuse
Solution: Constraint specification is needed, so interfaces are defined, code reuse is needed, so generics 1. Interface: In object-oriented programming, an interface is a specification definition that defines the behavior and actions of a class. 2. Generics: Generics address the reuse of class interface methods.
interface DBI<T> {
add(info: T): boolean;
update((info: T, id: number): boolean;
delete(id: number): boolean;
get(id: number): any[];
}
// Define a class that operates on the mysql database
// Note: To implement a generic interface, this class should also be generic
class MysqlDb<T> implements DBI<T> {
add(info: T): boolean {
console.log(info);
return true;
}
update(info: T, id: number): boolean {
throw new Error('Method not implementes.')}delete(id: number): boolean {
throw new Error('Method not implementes.')
}
get(id: number): boolean {
throw new Error('Method not implementes.')}}// Define a MSSQL database class
class MsSqlDb<T> implements DBI<T> {
add(info: T): boolean {
console.log(info);
return true;
}
update(info: T, id: number): boolean {
throw new Error('Method not implementes.')}delete(id: number): boolean {
throw new Error('Method not implementes.')
}
get(id: number): boolean {
throw new Error('Method not implementes.')}}// Define a user class to map to the table
class User {
username: string | undefined;
password: string | undefined;
}
u.username = "Zhang";
u.password = 123;
// Use the class as an argument to constrain the type of data passed in
var mysql = new MysqlDb<User>();
mysql.add(u);
Copy the code
Modules in typescript
Modules: TypeScript modules are designed to be replaceable organization code. A module executes in its own scope, not in a global scope, which means that variables, functions, classes, and so on defined in a module are not visible outside the module unless they are explicitly exported using export. Similarly, we must import variables, functions, classes, and so on exported by other modules through import. The relationship between the two modules is established by using import and export at the file level. A module uses the module loader to import other modules. At run time, the module loader’s job is to find and execute all of the module’s dependencies before executing the module code. The most familiar JavaScript module loaders are CommonJS for Node.js and require.js for Web applications.
Concept: Separate common component functions into a single file as a module. Variables, functions, classes, etc. in modules are private by default. If we want to access data (variables, functions, classes, etc.) in modules externally, we need to expose data (variables, functions, classes, etc.) in modules through export. Importing a module after exposure allows you to use the data (variables, functions, classes, etc.) exposed in the module.
Export default getData is exposed by default. Note that the default exposure can only be used once in a module. Import getData form ‘./modules/db’;
Typescript namespace Namespace modularity
Namespace: Internal module used to organize code and avoid explicit conflicts. Module: Short for ts external module, focusing on code reuse. A module may have multiple namespaces.
// Expose the namespace when using it as a module
// export namespace A {}
Import {A} form './modules/ A ';
// var d = new A.Dog();
// d.eat();
namespace A {
// The method in the namespace is private by default. To use the method in the namespace outside, expose the method in the namespace export
export class Dog implements Animal {
eat() {
console.log(111); }}}var d = new A.Dog();
d.eat();
namespace B {
}
Copy the code
Decorators in typescript
Decorators: A decorator is a special type of declaration that can be attached to a class’s declarations, methods, attributes, or parameters to modify the behavior of the class.
In layman’s terms, a decorator is a method that can be injected to extend the functionality of a class, method, or property parameter.
Common decorators are class decorators, attribute decorators, method decorators, and parameter decorators.
Decorator is written as: normal decorator (can not be added), decorator factory (can be added).
Decorators have been one of js’s biggest achievements over the past few years and have become a standard feature of Es7.
Class decorator
The class decorator is 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.
Common decorator:
/ / a decorator
function logClass(params: any) {
// Params is the current class
console.log(params);
params.prototype.apiUrl = 'XXX';
}
// Call decorator (no parameter decorator, be careful not to use semicolons after decorator calls)
@logClass
class HttpClient {
constructor(){}getData(){}}// View an instance of the current class
var http:any = new HttpClient();
console.log(http.api); // Prints the dynamically extended property XXX
Copy the code
Decoration factory:
function logClass(params: string) {
return function(target: any) {
console.log(target);
console.log(params);
params.prototype.apiUrl = 'XXX'; }}// Call the decorator
// Assign xiaochen to params and the HttpClient class to target
@logClass('xiaochen')
class HttpClient {
constructor(){}getData(){}}// View an instance of the current class
var http:any = new HttpClient();
console.log(http.api); // Prints the dynamically extended property XXX
Copy the code
Class decorator reloads constructors: Class decorator expressions are called at run time as functions, 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 class.
function logClass(target: any) {
console.log(target);
return class extends target {
apiUrl:any = 'I'm the modified data.';
}
getData() {
console.log(this.apiUrl);
}
}
@logClass
class HttpClient {
public apiUrl: string | undefined;
constructor() {
this.apiUrl = 'I'm the apiUrl inside the constructor';
}
getData() {
console.log(this.apiUrl); }}// View an instance of the current class
var http:any = new HttpClient();
console.log(http.api); // Print out the modified data
Copy the code
Attribute decorator
The property decorator expression is called at run time as a function, passing in the following two arguments: 1. Class constructor for static members, class prototype object for instance members 2. Name of member
// Class decorator
function logClass(params: string) {
return function(target: any) {
console.log(target);
console.log(params); }}// Attribute decorator
function logProperty(params: string) {
// The target class prototype object
return function(target: any, attr: any) {
console.log(target);
console.log(attr);
// The target inside the property decorator is equivalent to the target.prototype inside the class decorator
// It is the prototype object of the class. You can modify the properties of the prototype objecttarget[attr]= params; }}// Call the decorator
@logClass('XXX')
class HttpClient {
// Note: Decorators do not need semicolons after them
@logProperty('HHHHHHH')
public apiUrl: string | undefined;
constructor(){}getData() {
console.log(apiUrl); }}// View an instance of the current class
var http:any = new HttpClient();
http.getData(); // Print the output HHHHHHH
Copy the code
Method decorator
It is applied to method property descriptions and can be used to monitor, modify, or replace method definitions. Method decorators pass in the following three arguments at runtime: (1) constructor of class for static members, (2) prototype object for instance members. Name of the member 3. Attribute descriptor of the member
/ / a decorator
function logMethod(params: any) {
return function(target: any, methodName: any, desc: any) {
console.log(target); // Prototype objects
console.log(methodName); // Member name getData
console.log(desc); / / descriptors
// Modify the decorator method
console.log(desc.value); //getData() {console.log(apiUrl); }
// The decorator method modifies all arguments passed in the decorator method to string
// Save the current method
var oMethod = desc.value;
desc.value = function(. args: any[]) {
args = arga.map((value) = > {
return String(value);
})
// Print out all the parameters
console.log(args);
oMethod.apply(this, args); // We can print both the output value from the getData method and the incoming data value}}}class HttpClient {
// Note: Decorators do not need semicolons after them
@logMethod('Hahaha what happened to the developer's technology docking')
public apiUrl: string | undefined;
constructor(){}getData(. args: any[]) {
console.log(args);
console.log('I'm a method in getData'); }}// View an instance of the current class
var http:any = new HttpClient();
http.getData(123.'XXX')
Copy the code
Method parameter decorator
The parameter decorator expression is called as a function at run time. You can use the parameter decorator to add some element data to the class’s prototype, passing in the following three parameters:
- The constructor of the class for static members and the prototype object for instance members
- Method name
- The index of a parameter in the function argument list
function logMethod(params: any) {
return function(target: any, paramsName: any, paramsIndex: any) {
console.log(params); // Prints the uid
console.log(target); // Prototype objects
console.log(paramsName); // Method name -- getData
console.log(paramsIndex); // index -- 12333
target.apiUrl = params;
}
class HttpClient {
public apiUrl: string | undefined;
constructor(){}getData(@logMethod('uid') uid: any) {
console.log(args);
console.log('I'm a method in getData'); }}// View an instance of the current class
var http:any = new HttpClient();
http.getData(12333);
// Prints out the apiUrl
console.log(http.apiUrl); // Prints the uid
Copy the code
The order in which decorators are executed
- Attribute decorator
- Method decorator
- Method parameter decorators (executed from back to front when there are multiple of the same decorators)
- Class decorator