- Mastering TypeScript 3
- Nathan Rozentals
- 481字
- 2021-07-02 12:42:39
Default project settings
Once a new Empty ASP.NET web application has been created, we can start adding files to the project by right-clicking on the project itself, and selecting Add then New Item. There are two files that we are going to add to the project, namely, an index.html file, and an app.ts TypeScript file. For each of these files, select the corresponding Visual Studio template, as follows:
We can now open up the app.ts file and start typing the following code:
class MyClass { public render(divId: string, text: string) { var el: HTMLElement = document.getElementById(divId); el.innerText = text; } } window.onload = () => { var myClass = new MyClass(); myClass.render("content", "Hello World"); };
Here, we have created a class named MyClass, that has a single render function. This function takes two parameters, named divId and text. The function finds an HTML DOM element that matches the divId argument, and then sets the innerText property to the value of the text argument. We then define a function to be called when the browser calls window.onload. This function creates a new instance of the MyClass class, and calls the render function.
You will notice that Visual Studio has very powerful Intellisense options, and will suggest code, function names, or variable names as and when you are typing your code. If they are not automatically appearing, then hitting Ctrl+spacebar will bring up the Intellisense options for the code you are currently typing.
With our app.ts file in place, we can compile it by hitting Ctrl+Shift+B, or F6, or by selecting the Build option from the toolbar. If there are any errors in the TypesScript code that we are compiling, Visual Studio will automatically pop up an Error List panel, showing current compilation errors. Double-clicking on any one of these errors will bring up the file in the editor panel, and automatically move the cursor to the offending code.
To include our TypeScript file in the HTML page, we will need to edit the index.html file, and add a <script> tag to load app.js, as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script src="app.js"></script> </head> <body> <div id="content"></div> </body> </html>
Here, we have added the <script> tag to load our app.js file, and have also created a <div> element with the id of content. This is the DOM element that our code will modify the innerHtml property of. We can now hit F5 to run our application: