House
/
Blog
/
TypeScript vs JavaScript: Understanding the Differences

TypeScript vs JavaScript: Understanding the Differences

If you’ve been a JavaScript developer for a little while, you’ve probably read or heard about TypeScript.

TypeScript vs JavaScript: Understanding the Differences

If you’ve been a JavaScript developer for a little while, you’ve probably read or heard about TypeScript. You might be wondering whether it is something that you might need or have any interest in and may even ask yourself whether it is one of those hyped new techs or JS libraries and frameworks that the cool kids are talking about that would probably die within a few months if not weeks. If you did, then let me assure you that it’s not one of them. In the next couple of sections, I’ll be talking about what it is, what you can do with it, how to get started, what it’s not, and whether you should choose it over your beloved good ol’ JavaScript. But before we go further, what is TypeScript exactly?

TypeScript is defined as a programming language that is a strict syntactical superset of JavaScript and adds optional static typing to the language. It is designed for the development of large applications and transcompiles to JavaScript. It was created by Microsoft and first appeared in 2012.

A superset of JavaScript. What does that mean? Well, it means that all JavaScript code is valid TypeScript. Why? Because the types are optional. Really? Yes. TypeScript also allows you to use the latest and greatest of the ECMAScript standard that may have not been implemented in the latest versions of the major browsers yet. 

Why TypeScript Is Useful

As you may know, JavaScript is weakly typed, which means that it will try to figure out what the type of your data is by itself. That can be really cool because you don’t have to know ahead of time all the different types that you will be using in your data structures. That can lead to high productivity for some developers. But that same advantage can be the source of a lot of bugs, issues, and lack of self-documenting code in larger codebases. Even with a good IDE like VS Code providing you autocompletion, IntelliSense, and whatnot, you’ll soon be shooting yourself in the foot involuntarily. Even if you are an experienced developer, because you are a human, you are prone to making errors anytime, any day. Enter TypeScript!

Just by changing your files’ extension from .js to .ts, most editors will offer better support for autocompletion, IntelliSense, more features, and safety. TypeScript won’t even compile if it detects an error that it knows about, syntactic errors being the most common.

What You Can Do With TypeScript

Anything that you can do with JavaScript, you can do with TypeScript. Building for the web, desktop, mobile, embedded, and more platforms will work just as fine if not better. That’s because all TypeScript code will at some point be compiled to JavaScript, mainly because there are no (official) TypeScript engines (yet). V8, the most popular JavaScript engine powering Node, Deno, Chrome, and other major platforms won’t seem to ever have support for TypeScript anyway. So how does TypeScript get translated to JavaScript to be read, parsed, and executed by a JS engine, you might ask. That’s what the next section discusses.

How to Get Started with TypeScript

TypeScript as stated earlier is a superset of JavaScript. It offers a little bit of a different syntax and more features that are not even implemented yet in the current browsers and platforms that support running JS. But how do you do that? Well, there are many ways to do that but one popular one is to use the typescript npm package. And this is what we will use in this guide. Make sure you have at least the recommended version of Node.js installed. You can install the package globally so it can be available everywhere in your terminal, or locally and it will be available just for the current npm project.

Go ahead and create a new folder in your working directory. Using your favorite terminal. "cd” into that directory and run npm init. Answer all the questions if you want or just press Enter on your keyboard to accept the defaults. Once done, a package.json file will be created. Now it’s time to install TypeScript. Run “npm install typescript” and wait for the installation to complete. The next step is to add a new script to your scripts section or just delete the existing one. Your package.json should look something like this:

Now if you run “npm run tsc”, you should see something like the image below:

That means TypeScript has been installed and is working properly. Now, let’s start using it. TypeScript can compile to JavaScript in different flavors. What that means is that you can choose which EcmaScript standards version you want to target. A common choice is ES5, but we’ll get to that in a second. Create the obligatory hello.ts file and write console.log(“Hello World!”) into it like so:


We’ve done nothing exciting yet. This code would work in plain JavaScript as well. But we just want to compile it. So how do we do that? Looking at what is displayed when you run npm run tsc, at the top we can see a small section with some examples. You’ll notice that you can run the tsc command with the name of the .ts file you want to compile. Let’s go ahead and run npm run tsc hello.ts. After less than a second it displays:

> ts@1.0.0 tsc

> tsc "hello.ts"

Now if you look closely in your project you can see that a new file has been created. It’s called hello.js. When we open the file we can see that it displays console.log(“Hello World!”). And running that file using Node.js, node hello.js, will display “Hello World!”. No big deal! Now let’s do something more interesting. We’ll create a function that adds two numbers together, and we’ll specify the types of the parameters and the return value of it. Create a new file called “add.ts” and add this code into it:


Depending on the IDE that you are using, I’m using VS Code, you will see the parameters underlined with dots. If you hover over any of them you will see a popup saying: 


What this means is that TypeScript will default to the “any” type in instances when it can’t figure out on its own what the type of variable or parameter is. TypeScript is smart enough to figure out the types for primitive types such as string, number, function, and object. But it will start guessing again when your data structure starts to have nested values. That’s because it can’t know by itself what data you will throw at it upfront unless you tell it. And when you tell it, you will help it to help you back. With that said, if you were to give default values to a and b, then TypeScript would stop complaining. For example:

That’s really useless but I hope you get the point.

That’s a lot more theory, but let’s run our code as-is. Run npm run tsc add.ts to compile this code to JavaScript. Doing so creates a new file called add.js in the same directory, and its content is as so:

Still no big deal! Running this code with Node.js, node add.js, will as expected display 3. So you may be wondering, how do I provide the types myself? Well to add types you need to add a colon “:” after a variable, parameter, or function name and specify the types. The TypeScript types can be any of these:

  • string
  • number
  • boolean
  • Array
  • any
  • functions
  • Object types
  • Union types

Today we’ll use some of the primitive ones in a few examples. Let’s type “a” and “b” as numbers so TypeScript can know what to expect like so:

Once we do that, we’ll be good to go. But we can still return any other type from that function. 

And TypeScript won’t even complain. More often than not you would want to return the sum of the two numbers instead of a string, right? Then we can get TypeScript to help us here as well. We can type the function:

If we try to return another type of value other than a number, TypeScript will now complain saying “Type 'string' is not assignable to type 'number'”. It knows that it has to return a number and not a string, so it protects us from doing something unexpected. We can just return the sum of a and b as usual and it will work. Let’s try to compile this function and see what we get. Run npm run tsc add.ts and open the compiled add.js file. What do you see? You should see something like this:


Notice that TypeScript has gotten rid of the types. And then we can run this code as usual and we’ll get 3. Now you can see how TypeScript can help you write better code and make fewer errors during development. That’s because TypeScript is inexistent when your code is compiled. You are left with plain ol’ (or new if you choose so) JavaScript code.


Let’s try to mess with the parameters’ value types and see what we get. When calling add, let’s feed it with two strings instead of numbers. What did you see? Yes, TypeScript is complaining again. But this time, where we call the function on the first parameter saying: “Argument of type 'string' is not assignable to parameter of type 'number'”.

If you try to compile this code as-is it will fail. Let’s try a few more examples. Create a new file called examples.ts and paste the following code in it:


Play with it and see what you get. 

Okay, this is all good, but how do we configure it? To configure it, you need to use a “tsconfig.json” file in the root of your directory. It is a JSON file that TypeScript will read and configure itself depending on the values of that file. For example, if you use the arrow function instead of the function keyword to declare a function, TypeScript will by default convert it to the function keyword version, but using tsconfig.json you can specify the target to be es6 instead and TypeScript will leave it as-is. Of course, you have to make sure that the platform(s) that will run your code has (have) support for that version. Head over to the docs for more info on how to work with tsconfig.json.

What TypeScript Is Not

Once you start to see all the benefits that TypeScript provides over JavaScript, you’ll tend to stop writing JavaScript entirely and that’s fine. You might think you can stop writing tests because TypeScript helps you catch so many errors in your code. Don’t do that. TypeScript will help with syntax and obvious type errors where possible. It won’t help with logical errors. For example, if you are building a program that calculates a 10% tax on an order at a restaurant, and instead of adding the 10% on the total you subtract it from it, then that error is on you, not TypeScript. It can’t know what your business logic is. You should know that. And you will make the restaurant lose a lot of money and even go bankrupt because of that. Kind of overdramatized, I know.

TypeScript vs JavaScript

Despite all the advantages that TypeScript offers developers, not everyone will be happy with it or like it. It can be daunting for beginners and can slow productivity for experienced programmers. “What do you mean I need to add a type to everything before I even start using them?”, you might hear a developer shout. ;) That’s fine. It’s not for everyone. But in this day and age, most respectable, large projects (especially in enterprise) will be using or are already in the process of using TypeScript. As a developer, even if you don’t plan to use it for your own side projects and projects that you have control over entirely, learning TypeScript can be really useful. If you plan on working at the enterprise level, you will be required to write TypeScript anyway, whether you want it or not. So there’s never been a better time to be a TypeScript (and/or JavaScript) programmer. 

Further Resources For Learning TypeScript

https://www.typescriptlang.org/

https://kentcdodds.com/blog/typescript-function-syntaxes

https://robertcooper.me/post/get-started-with-typescript-in-2019

https://github.com/DefinitelyTyped/DefinitelyTyped

https://www.npmjs.com/package/typescript

https://codeburst.io/understanding-typescript-basics-e003dbad2191?gi=65f92f89c8bf


House
/
Blog
/

TypeScript vs JavaScript: Understanding the Differences

TypeScript vs JavaScript: Understanding the Differences
If you’ve been a JavaScript developer for a little while, you’ve probably read or heard about TypeScript.

If you’ve been a JavaScript developer for a little while, you’ve probably read or heard about TypeScript. You might be wondering whether it is something that you might need or have any interest in and may even ask yourself whether it is one of those hyped new techs or JS libraries and frameworks that the cool kids are talking about that would probably die within a few months if not weeks. If you did, then let me assure you that it’s not one of them. In the next couple of sections, I’ll be talking about what it is, what you can do with it, how to get started, what it’s not, and whether you should choose it over your beloved good ol’ JavaScript. But before we go further, what is TypeScript exactly?

TypeScript is defined as a programming language that is a strict syntactical superset of JavaScript and adds optional static typing to the language. It is designed for the development of large applications and transcompiles to JavaScript. It was created by Microsoft and first appeared in 2012.

A superset of JavaScript. What does that mean? Well, it means that all JavaScript code is valid TypeScript. Why? Because the types are optional. Really? Yes. TypeScript also allows you to use the latest and greatest of the ECMAScript standard that may have not been implemented in the latest versions of the major browsers yet. 

Why TypeScript Is Useful

As you may know, JavaScript is weakly typed, which means that it will try to figure out what the type of your data is by itself. That can be really cool because you don’t have to know ahead of time all the different types that you will be using in your data structures. That can lead to high productivity for some developers. But that same advantage can be the source of a lot of bugs, issues, and lack of self-documenting code in larger codebases. Even with a good IDE like VS Code providing you autocompletion, IntelliSense, and whatnot, you’ll soon be shooting yourself in the foot involuntarily. Even if you are an experienced developer, because you are a human, you are prone to making errors anytime, any day. Enter TypeScript!

Just by changing your files’ extension from .js to .ts, most editors will offer better support for autocompletion, IntelliSense, more features, and safety. TypeScript won’t even compile if it detects an error that it knows about, syntactic errors being the most common.

What You Can Do With TypeScript

Anything that you can do with JavaScript, you can do with TypeScript. Building for the web, desktop, mobile, embedded, and more platforms will work just as fine if not better. That’s because all TypeScript code will at some point be compiled to JavaScript, mainly because there are no (official) TypeScript engines (yet). V8, the most popular JavaScript engine powering Node, Deno, Chrome, and other major platforms won’t seem to ever have support for TypeScript anyway. So how does TypeScript get translated to JavaScript to be read, parsed, and executed by a JS engine, you might ask. That’s what the next section discusses.

How to Get Started with TypeScript

TypeScript as stated earlier is a superset of JavaScript. It offers a little bit of a different syntax and more features that are not even implemented yet in the current browsers and platforms that support running JS. But how do you do that? Well, there are many ways to do that but one popular one is to use the typescript npm package. And this is what we will use in this guide. Make sure you have at least the recommended version of Node.js installed. You can install the package globally so it can be available everywhere in your terminal, or locally and it will be available just for the current npm project.

Go ahead and create a new folder in your working directory. Using your favorite terminal. "cd” into that directory and run npm init. Answer all the questions if you want or just press Enter on your keyboard to accept the defaults. Once done, a package.json file will be created. Now it’s time to install TypeScript. Run “npm install typescript” and wait for the installation to complete. The next step is to add a new script to your scripts section or just delete the existing one. Your package.json should look something like this:

Now if you run “npm run tsc”, you should see something like the image below:

That means TypeScript has been installed and is working properly. Now, let’s start using it. TypeScript can compile to JavaScript in different flavors. What that means is that you can choose which EcmaScript standards version you want to target. A common choice is ES5, but we’ll get to that in a second. Create the obligatory hello.ts file and write console.log(“Hello World!”) into it like so:


We’ve done nothing exciting yet. This code would work in plain JavaScript as well. But we just want to compile it. So how do we do that? Looking at what is displayed when you run npm run tsc, at the top we can see a small section with some examples. You’ll notice that you can run the tsc command with the name of the .ts file you want to compile. Let’s go ahead and run npm run tsc hello.ts. After less than a second it displays:

> ts@1.0.0 tsc

> tsc "hello.ts"

Now if you look closely in your project you can see that a new file has been created. It’s called hello.js. When we open the file we can see that it displays console.log(“Hello World!”). And running that file using Node.js, node hello.js, will display “Hello World!”. No big deal! Now let’s do something more interesting. We’ll create a function that adds two numbers together, and we’ll specify the types of the parameters and the return value of it. Create a new file called “add.ts” and add this code into it:


Depending on the IDE that you are using, I’m using VS Code, you will see the parameters underlined with dots. If you hover over any of them you will see a popup saying: 


What this means is that TypeScript will default to the “any” type in instances when it can’t figure out on its own what the type of variable or parameter is. TypeScript is smart enough to figure out the types for primitive types such as string, number, function, and object. But it will start guessing again when your data structure starts to have nested values. That’s because it can’t know by itself what data you will throw at it upfront unless you tell it. And when you tell it, you will help it to help you back. With that said, if you were to give default values to a and b, then TypeScript would stop complaining. For example:

That’s really useless but I hope you get the point.

That’s a lot more theory, but let’s run our code as-is. Run npm run tsc add.ts to compile this code to JavaScript. Doing so creates a new file called add.js in the same directory, and its content is as so:

Still no big deal! Running this code with Node.js, node add.js, will as expected display 3. So you may be wondering, how do I provide the types myself? Well to add types you need to add a colon “:” after a variable, parameter, or function name and specify the types. The TypeScript types can be any of these:

  • string
  • number
  • boolean
  • Array
  • any
  • functions
  • Object types
  • Union types

Today we’ll use some of the primitive ones in a few examples. Let’s type “a” and “b” as numbers so TypeScript can know what to expect like so:

Once we do that, we’ll be good to go. But we can still return any other type from that function. 

And TypeScript won’t even complain. More often than not you would want to return the sum of the two numbers instead of a string, right? Then we can get TypeScript to help us here as well. We can type the function:

If we try to return another type of value other than a number, TypeScript will now complain saying “Type 'string' is not assignable to type 'number'”. It knows that it has to return a number and not a string, so it protects us from doing something unexpected. We can just return the sum of a and b as usual and it will work. Let’s try to compile this function and see what we get. Run npm run tsc add.ts and open the compiled add.js file. What do you see? You should see something like this:


Notice that TypeScript has gotten rid of the types. And then we can run this code as usual and we’ll get 3. Now you can see how TypeScript can help you write better code and make fewer errors during development. That’s because TypeScript is inexistent when your code is compiled. You are left with plain ol’ (or new if you choose so) JavaScript code.


Let’s try to mess with the parameters’ value types and see what we get. When calling add, let’s feed it with two strings instead of numbers. What did you see? Yes, TypeScript is complaining again. But this time, where we call the function on the first parameter saying: “Argument of type 'string' is not assignable to parameter of type 'number'”.

If you try to compile this code as-is it will fail. Let’s try a few more examples. Create a new file called examples.ts and paste the following code in it:


Play with it and see what you get. 

Okay, this is all good, but how do we configure it? To configure it, you need to use a “tsconfig.json” file in the root of your directory. It is a JSON file that TypeScript will read and configure itself depending on the values of that file. For example, if you use the arrow function instead of the function keyword to declare a function, TypeScript will by default convert it to the function keyword version, but using tsconfig.json you can specify the target to be es6 instead and TypeScript will leave it as-is. Of course, you have to make sure that the platform(s) that will run your code has (have) support for that version. Head over to the docs for more info on how to work with tsconfig.json.

What TypeScript Is Not

Once you start to see all the benefits that TypeScript provides over JavaScript, you’ll tend to stop writing JavaScript entirely and that’s fine. You might think you can stop writing tests because TypeScript helps you catch so many errors in your code. Don’t do that. TypeScript will help with syntax and obvious type errors where possible. It won’t help with logical errors. For example, if you are building a program that calculates a 10% tax on an order at a restaurant, and instead of adding the 10% on the total you subtract it from it, then that error is on you, not TypeScript. It can’t know what your business logic is. You should know that. And you will make the restaurant lose a lot of money and even go bankrupt because of that. Kind of overdramatized, I know.

TypeScript vs JavaScript

Despite all the advantages that TypeScript offers developers, not everyone will be happy with it or like it. It can be daunting for beginners and can slow productivity for experienced programmers. “What do you mean I need to add a type to everything before I even start using them?”, you might hear a developer shout. ;) That’s fine. It’s not for everyone. But in this day and age, most respectable, large projects (especially in enterprise) will be using or are already in the process of using TypeScript. As a developer, even if you don’t plan to use it for your own side projects and projects that you have control over entirely, learning TypeScript can be really useful. If you plan on working at the enterprise level, you will be required to write TypeScript anyway, whether you want it or not. So there’s never been a better time to be a TypeScript (and/or JavaScript) programmer. 

Further Resources For Learning TypeScript

https://www.typescriptlang.org/

https://kentcdodds.com/blog/typescript-function-syntaxes

https://robertcooper.me/post/get-started-with-typescript-in-2019

https://github.com/DefinitelyTyped/DefinitelyTyped

https://www.npmjs.com/package/typescript

https://codeburst.io/understanding-typescript-basics-e003dbad2191?gi=65f92f89c8bf


React

Hire vetted remote developers today

Technology leaders rely on G2i to hire freelance software developers, find full-time engineers, and build entire teams.

Group

More from G2i