How to Create Class in TypeScript

Class in TypeScript

 
A class declaration declares a class instance type and a constructor function, both with the name given by Identifier, in the containing module. The class instance type is created from the instance members declared in the class body and the instance members inherited from the base class. The constructor function is created from the constructor declaration, the static member declarations in the class body, and the static members inherited from the base class.
 
The constructor function initializes and returns an instance of the class instance type.
 
The following example shows how to create and use a class in TypeScript. The example prints "Hello C-sharp corner user....!".
 

Coding

 
classdemo.ts 
  1. class Greeter {  
  2.  greeting: string;  
  3.  constructor(message: string) {  
  4.   this.greeting = message;  
  5.  }  
  6.  greet() {  
  7.   return "Hello, " + this.greeting;  
  8.  }  
  9. }  
  10. var greeter = new Greeter("C-sharpcorner user.....!");  
  11. var button = document.createElement('button')  
  12. button.onclick = function() {  
  13.  alert(greeter.greet())  
  14. }  
  15. document.body.appendChild(button)   
classdemo.html
  1. <html>  
  2.     <head></head>  
  3.     <body>  
  4.         <h1>TypeScript Class Example</h1>  
  5.         <script>var Greeter = (function () {    
  6. function Greeter(message) {    
  7. this.greeting = message;    
  8. }    
  9. Greeter.prototype.greet = function () {    
  10. return"Hello, " + this.greeting;    
  11. };    
  12. return Greeter;    
  13. })();    
  14. var greeter = new Greeter("C-sharpcorner user.....!");    
  15. var button = document.createElement('button');    
  16. button.textContent = "Click On Me";    
  17. button.onclick = function () {    
  18. alert(greeter.greet());    
  19. };    
  20. document.body.appendChild(button);    
  21. </script>  
  22.     </body>  
  23. </html>   
app.js 
  1. var Greeter = (function() {  
  2.  function Greeter(message) {  
  3.   this.greeting = message;  
  4.  }  
  5.  Greeter.prototype.greet = function() {  
  6.   return "Hello, " + this.greeting;  
  7.  };  
  8.  return Greeter;  
  9. })();  
  10. var greeter = new Greeter("C-sharpcorner user.....!");  
  11. var button = document.createElement('button');  
  12. button.onclick = function() {  
  13.  alert(greeter.greet());  
  14. };  
  15. document.body.appendChild(button);   
The output looks like the following:
 
class-type-script.gif
 
 In this simple code example, we saw how to declare and use a class in TypeScript.


Similar Articles