In recent work, take note: Suppose we need a function, the output of a number such as 10000 to the following string format "10,000", generally write a method, then I would like to more convenient, directly add a format method to the # type, For example, a method called Toformat to implement a formatted string.
Add a. D.ts definition
The method to extend a base object in typescript requires that the compiler have this method in advance:
1 interface Number {2 Toformat (): string; 3 }
Add implementation
The specific implementation can be written as needed, and it is important to note that the prototype object is added to the line:
1Number.property.toFormat =function () {2 //get the value of the number, i.e. the number itself3 varValue = This. ValueOf ();4 //here is the specific handling code, which is skipped here5 varstr = "Code";6 //return and then7 returnstr;8}
You can call it directly:
1 var i = 10000; 2 Console.log (I.toformat ());
My implementation here is written in JavaScript, and if it is in typescript, it can be written using TS.
Extending the functionality of the JavaScript base object in Typescript