I decided to write this article simply because there are so many outdated answers to this question linked from Google. Suppose you are starting a new project. Here are some of the things you should NOT do:
Right click on Project -> Add -> New Item... -> under "Search Installed Templates" in the top right corner search for "types" and select "TypeScript File" from the list, call it "script.ts" for now and click "Add" (the name can be anything you want). Notice the file should have a .ts extension. If you are wondering - yes, you will still have typings for standard Javascript objects, and I will prove it later on. You are done! Typescript should be fully operational at this point. Let's see how to make it do some useful work. First, we need to verify that Visual Studio can transpile into Javascript. In your .ts file type alert("Hello"); and hit save (CTRL+S). Nothing happened? Where is my .js file? Okay, the transpiled .js file is hidden by default. You need to click "Show all files" icon in Solution Explorer: We are going to add a .html page to be able to see it working inside the browser. Right click Project -> Add -> New Item... -> search for "html", select "HTML Page", name it Default.html and click Add. Put "Hello World" between the body open/close tags just so we can see something when it loads. Press F5 or click the green "play" button to start the project. When it loads in your browser, you should see something like this: It works. Now close the browser window and go back to your Default.html file. Right before the closing </head> tag make a newline. Drag a .ts file into that line. It should paste something like this: <script src="script.js"></script> Yes, you could have typed this manually, but it would not be as cool. In your script you have an alert, so that's what you are supposed to see when you start your project again. Ok, but we didn't do any TypeScript yet? Go inside your .ts file and paste the following: class SayHello { name: string; constructor(name: string) { this.name = name; } sayHello() { alert("Hello, " + this.name); } } var a = new SayHello("Victor"); a.sayHello(); Hit save (CTRL+S) and... actually, there is one more thing to do. Right click on "Default.html" and choose "Set as Startup Page", this way we just save a few clicks. There: Now I promised to prove that we have typings and also show the debugging support (because it would be quite useless without it). Back to your .ts file at the very bottom type "document.get": Notice the argument is expected to be of type "string". Our typings work, you now have typed intellisense support for standard Javascript objects. Remove this line and put a breakpoint inside the class beside the "alert" line and run it again.See, debugging works just as fine as with a regular Javascript file, which means real coding can start now! The rest you should be able to figure out using google. Any questions or comments - shoot me an email. |
Tech Blog >