close icon
daily.dev platform

Discover more from daily.dev

Personalized news feed, dev communities and search, much better than whatโ€™s out there. Maybe ;)

Start reading - Free forever
Start reading - Free forever
Continue reading >

Compile TS to JS: A Beginner's Guide

Compile TS to JS: A Beginner's Guide
Author
Nimrod Kramer
Related tags on daily.dev
toc
Table of contents
arrow-down

๐ŸŽฏ

Learn how to compile TypeScript code into JavaScript, set up your development environment, write your first TypeScript program, and explore advanced features to enhance your coding skills.

If you're new to TypeScript and wondering how to turn your TS code into JS, you're in the right place. This beginner's guide will walk you through the basics of TypeScript, a powerful tool that enhances JavaScript with types, and show you how to compile TS to JS, making your code ready for any web browser. Here's what we'll cover:

  • Installing TypeScript: Get your development environment ready.
  • Writing TypeScript Code: Learn the syntax and write your first program.
  • Compiling TS to JS: Use the TypeScript compiler to transform your code.
  • Running and Debugging: Execute your JavaScript and troubleshoot any issues.
  • Exploring Advanced Features: Dive into generics, decorators, and more to unlock the full potential of TypeScript.

By the end of this guide, you'll have a solid foundation to start using TypeScript in your projects, enhancing the reliability and maintainability of your JavaScript code. Let's get started!

Relationship to JavaScript

Think of TypeScript as a buddy to JavaScript. It has everything JavaScript does, plus a bit more. The extra bit is mainly about types - TypeScript checks that you're using the right types of data everywhere in your code, something JavaScript doesn't do.

This means you can use your normal JavaScript code in TypeScript without changing anything. But, with TypeScript, you get extra checks that help find and fix mistakes before they cause problems.

Key Benefits

Here's why TypeScript is pretty great:

  • Static Typing - You can tell TypeScript exactly what type of data you expect in parts of your code, helping spot mistakes early.
  • Enhanced Tooling - TypeScript works really well with code editors, giving you features like auto-complete and error detection that make coding faster and less error-prone.
  • Better Readability - Adding types to your code acts like comments that explain what the code is supposed to do, making it easier for you and others to understand.
  • Increased Reliability - With TypeScript catching errors early and making sure your code is consistent, your projects are less likely to have bugs.
  • Gradual Adoption - You don't have to switch everything to TypeScript at once. You can start using it bit by bit in your existing JavaScript projects.

Setting Up the Development Environment

Installing Node.js and npm

Node.js

Before you dive into TypeScript, you need to set up Node.js and npm on your computer. Here's how:

  • Visit nodejs.org and download the LTS (Long Term Support) version of Node.js for your system. This step also installs npm, which is a tool you'll use to manage packages like TypeScript.
  • After installing, open your terminal or command prompt and type these commands to make sure Node.js and npm are ready to go:
node -v
npm -v 

If you see version numbers appear, you're all set.

Installing TypeScript

Now that you have npm, installing TypeScript is easy. Just type this command:

npm install -g typescript

This command installs the TypeScript compiler (basically a tool called tsc that turns your TypeScript code into JavaScript) on your computer.

To check if it worked, type:

tsc --version

If you see a version number, then TypeScript is ready to use.

That's it for the setup! You now have Node.js, npm, and TypeScript installed, which are the basic tools you need to start working on a TypeScript project.

Your First TypeScript Program

Let's dive into making a simple TypeScript program. We'll see how it looks and learn to change it into JavaScript.

Basic TypeScript Syntax

TypeScript adds rules about what kind of data you can use in your code, on top of what JavaScript already does. This helps catch mistakes early.

Here's a basic example of TypeScript code:

function greet(name: string) {
  return "Hello " + name;
}

let message = greet("John");
  • name: string means that the name must always be text.
  • string after function tells us what the function gives back, which is also text.
  • We use let to say there's a new piece of data named message.

TypeScript has several types like:

  • number for any kind of number
  • string for text
  • boolean for true or false
  • any for when the type doesn't matter

Compiling with tsc

To change our TypeScript code into JavaScript, we use a command:

tsc greet.ts

This creates a new file named greet.js that looks like:

function greet(name) {
    return "Hello " + name;
}
var message = greet("John");

You'll see the type instructions are gone.

You can set up rules for how to compile your code in a file named tsconfig.json. For instance, to put all the JavaScript files into a folder named build, you'd write:

"outDir": "./build" 

Running Compiled JavaScript

To run the JavaScript version of our program, type:

node build/greet.js

This lets us run the program we wrote in TypeScript, but now it's in the form of regular JavaScript.

Debugging and Troubleshooting

When you're working with TypeScript, sometimes things don't go as planned. Here's how to find and fix problems.

Common Compile-time Errors

You might run into a few usual issues when compiling TypeScript to JavaScript:

  • Type mismatches - This happens if you try to use a number where your code expects text, or vice versa. For example:
let name: string;
name = 5; // Error, can't use a number here

To solve this, make sure the data types match. If it's not important, you can use any to avoid specifying a type.

  • Undefined variables - If you use a variable that you haven't set up yet, you'll get an error:
console.log(someVariable); // Error, because someVariable doesn't exist

Check your spelling and make sure you've set up your variables before using them.

  • Syntax errors - These are just mistakes in how you wrote your code, like missing a comma or a bracket. The error messages will help you find where you went wrong.

Debugging with Source Maps

Source Maps

Source maps help you debug your TypeScript by connecting the dots back to your original .ts files, not the compiled .js ones.

To use them:

  • Compile TypeScript with the --sourcemap option
  • Or, in your tsconfig.json, set "sourceMap": true
  • Your debugger will now show your .ts files, making it easier to find and fix problems.

With source maps, you can see your original TypeScript code while debugging, making it much simpler to understand what's going on.

sbb-itb-bfaad5b

Advanced Features

TypeScript has some cool extra tools that make it even more powerful than regular JavaScript. These tools help you write code that can do more things and work in different ways.

When you turn TypeScript code with these extra tools into JavaScript, the special TypeScript parts are taken out. But the abilities those tools gave your code are still there in the JavaScript version, so browsers can run it without any trouble.

Generics

Generics let your functions and classes handle many types of data in a smart way.

For example, you can make a function that can return any type of data you give it:

function identity<T>(arg: T): T {
  return arg;
}

let output = identity<string>("Hello world");

Here T is like a placeholder for any type of data. When turned into JavaScript, generics are removed, leaving just:

function identity(arg) {
  return arg; 
}

let output = identity("Hello world");

Generics help you write code that can be used in many ways, while still keeping the JavaScript simple.

Decorators

Decorators let you change or add to how classes work in an easy way.

For example, you can make a decorator that tells you whenever a method is used:

function Log(target, propertyKey, descriptor) {
  let original = descriptor.value;

  descriptor.value = function(...args) {
    console.log("Method called");
    return original.apply(this, args);
  }

  return descriptor;
}

class Calculator {
  @Log
  add(a, b) {
    return a + b;
  }
}

The @Log decorator changes the add() method to print a message every time it's used. After compiling, decorators are gone but they leave behind useful changes to how classes work.

Union Types

Union types let you use different types of data for the same value.

For example, you might have a function that can take either a number or a string:

function printId(id: number | string) {
  console.log("Your ID is: " + id); 
}

printId(101); // Okay  
printId("202"); // Okay

The number | string means id can be a number or a string. In JavaScript, this turns into normal code without type checks:

function printId(id) {
  console.log("Your ID is: " + id);  
}

printId(101);
printId("202"); 

So, union types let your code accept different kinds of inputs, while still making sure it works as regular JavaScript.

Overall, TypeScriptโ€™s extra tools give you new ways to write code that is reusable and flexible, all while making sure it turns into JavaScript that works everywhere. They're great for writing code that can do a lot of different things.

Tools and IDEs

Visual Studio Code, or VS Code, is a favorite tool for working with TypeScript. It's got some cool features that make coding easier:

VS Code Extensions

VS Code can be made even better with add-ons called extensions. Here are a few good ones for TypeScript:

  • TypeScript Hero - Helps tidy up your imports and adds any that you forgot, making things neater.
  • TypeScript Importer - Finds and adds import statements for you, saving time.
  • Path Autocomplete - Completes the names of files for you so you don't make mistakes typing them.

Built-in TypeScript Support

VS Code comes with some great TypeScript features already built in:

  • IntelliSense - Helps you write code faster by completing it for you and showing info about the code you're using.
  • Error Checking - Points out mistakes and warnings while you're writing, so you can fix them on the spot.
  • Refactoring - Lets you change your code around easily, like renaming things or organizing them better.
  • Debugging - You can pause your code to see what's going on, step through it line by line, and check out data.

VS Code automatically compiles your TypeScript into JavaScript with tsc, which means you can test your code directly from the editor.

In short, VS Code and its extensions make working with TypeScript much smoother. You get help as you type, find and fix mistakes quickly, and can change your code easily when you need to. It's a free and simple option that's packed with features for TypeScript coding.

Other editors like WebStorm, Atom, and Sublime Text are also good for TypeScript if you add the right plugins. But VS Code stands out because it's free, not too heavy, and has everything you need for TypeScript built right in.

Conclusion

Turning TypeScript into JavaScript is a key step in getting your code ready for the real world. If you've followed this guide from the start, you now know how to:

  • Install TypeScript and get your computer ready for coding
  • Write simple TypeScript code using types
  • Use the tsc (TypeScript compiler) to change TypeScript code into JavaScript
  • Run the JavaScript code you made with Node.js
  • Find and fix problems in your code with the help of source maps
  • Try out cool features like generics and decorators to do more with your code

As you keep learning TypeScript, you might want to try:

  • Adding TypeScript to web projects using React or Angular
  • Creating apps that use TypeScript both on the server side and in the browser
  • Using tools like Webpack to get your TypeScript code ready for visitors
  • Turning on stricter checks to catch more mistakes
  • Using TypeScript with libraries from other people to help find errors

Learning TypeScript bit by bit can really make your code better, help your team work together smoothly, and make your apps more reliable. It's worth the effort for the benefits it brings.

We hope this guide made it easier for you to start with TypeScript and turning it into JavaScript. Happy coding on your TypeScript adventure!

How to compile from ts to js?

To change TypeScript into JavaScript:

  • Open a TS file in VS Code.
  • Use the TypeScript build task (Ctrl+Shift+B) to run the compiler.
  • Set the TypeScript build as the default task.
  • Check the output for any issues.

The ts compiler will turn your TypeScript code into regular JavaScript that works in any web browser.

How to introduce TypeScript to a JavaScript project?

You can mix TypeScript files (.ts, .tsx) with your existing JavaScript files. Configure the ts compiler to put the JavaScript files it makes into your project's folder.

Can I learn ts without learning js?

No, it's important to know JavaScript first. TypeScript adds extra features like types to JavaScript, so understanding the basics of JavaScript is key to using TypeScript well.

Is TypeScript hard to learn if you know JavaScript?

TypeScript

If you're already familiar with JavaScript, learning TypeScript won't be much harder. It's pretty similar but adds things like types and interfaces. The main ideas and how you write code are largely the same.

Related posts

Why not level up your reading with

Stay up-to-date with the latest developer news every time you open a new tab.

Read more