Your First TypeScript File [Typescript Tutorial]

TypeScript requires extensions for its files. It uses either “.ts” or “.d.ts”

// setBackgroundColor.ts.
function setBackgroundColor() {
    document.body.style.backgroundColor = “rgb(255,0,0)”;
}
   
setBackgroundColor();

You might notice that it’s very similar to JavaScript. That’s because it is. Remember TypeScript is a superset of JavaScript. Pure JavaScript and the features of TypeScript that are declarative can be used. In the example, you can see the file is named as setBackgroundColor.ts

typescript

Next, the image shows how TypeScript files compile resulting in a JavaScript file with the same name. These files are compiled from command line using tsc command.

typescript

Here the .ts and .js are the same because the .ts file was written solely on JavaScript and without any TypeScript syntax. Remember that if your .ts file is pure JavaScript, the resulting .js file is the same as the .ts file.

function setBackgroundColor() {
    document.body.backgroundColor = “rgb(255,0,0)”;
}
   
setBackgroundColor();

Above is an invalid JavaScript file. Assuming you don’t want to create just TypeScript files and let it create .js files, you may want to consider working directly with .js files.

Next, the property backgroundColor isn’t supposed to be there. Assuming you wrote it in JavaScript, you won’t see the error until runtime. You have the option to tweak it with HTMLElement object’s prototype and create custom properties but that is a topic for some other time.

But if you use TypeScript:

TypeScript’s compiler immediately catches the syntax errors run in JavaScript.

typescript

Subscribe Now and Upgrade Your Skills Today!
Sign up now and have the latest tech tutorials delivered straight to your mailbox.

PLUS: Get exclusive member-only discounts (up to 80% OFF!!) on our top tech courses in Udemy!
We hate spam. Your email address will not be sold or shared with anyone else.