TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Let’s break down what exactly this means:
In this tutorial you will work with TypeScript in Visual Studio Code to explore the benefits of using them together.
For this project, you will need:
The first step toward working with TypeScript is to install the package globally on your computer. Install the typescript
package globally by running the following command in your terminal:
- npm install -g typescript
Next, run the following command to make a project directory:
- mkdir typescript_test
Move into the newly created directory:
- cd typescript_test
Now, you need to create a new TypeScript file. For reference, these end with the .ts
extension type.
You can now open up VS Code and create a new file by clicking File and then New File. After that, save it by clicking File and then Save As…. You can name this file app.ts
to follow this tutorial. The filename is not important, but ensuring the filetype extension of .ts
is.
The first line of this file should start with an export {};
for VS Code to recognize it as a module.
Create a function that will print the first and last name from a person
object:
export {};
function welcomePerson(person) {
console.log(`Hey ${person.firstName} ${person.lastName}`);
return `Hey ${person.firstName} ${person.lastName}`;
}
const james = {
firstName: "James",
lastName: "Quick"
};
welcomePerson(james);
The problem with the code above is that there is no restriction on what can be passed to the welcomePerson
function. In TypeScript, you can create interfaces that define what properties an object should have.
In the snippet below, there is an interface for a Person
object with two properties, firstName
and lastName
. Then, the welcomePerson
function was modified to accept only Person
objects.
export {};
function welcomePerson(person: Person) {
console.log(`Hey ${person.firstName} ${person.lastName}`);
return `Hey ${person.firstName} ${person.lastName}`;
}
const james = {
firstName: "James",
lastName: "Quick"
};
welcomePerson(james);
interface Person {
firstName: string;
lastName: string;
}
The benefit of this will become clear if you try to pass a string into the welcomePerson
function.
For example, replacing james
:
welcomePerson(james);
With 'James'
:
welcomePerson('James');
Because we are working with a TypeScript file, VS Code will immediately provide you feedback letting you know that the function expects a Person
object and not a string.
- OutputArgument of type '"James"' is not assignable to parameter of type 'Person'.
Now that you have a working TypeScript file, you can compile it to JavaScript. To do this you need to call the function and tell it which file to compile. You can utlize the built-in terminal in VS Code to do this.
- tsc app.ts
If you didn’t fix the error before, you’ll see an error output:
- Outputapp.ts:13:15 - error TS2345: Argument of type '"James"' is not assignable to parameter of type 'Person'.
Fix the error by passing the Person
object in correctly instead of a string. Then compile again, and you’ll get a valid JavaScript file.
Running an ls
command in the terminal will display the files in our current path:
ls
You will see your original ts
file and also a new js
file:
- Outputapp.js
- app.ts
Now, let’s open the app.js
file in VS Code.
"use strict";
exports.__esModule = true;
function welcomePerson(person) {
console.log("Hey " + person.firstName + " " + person.lastName);
return "Hey " + person.firstName + " " + person.lastName;
}
var james = {
firstName: "James",
lastName: "Quick"
};
welcomePerson(james);
Notice that the template literal strings, which are an ES6 feature, were compiled to simple string concatenation from ES5. We’ll come back to this shortly.
To verify that this worked, you can now run the JavaScript directly using Node in your terminal:
- node app.js
You will see a name printed to the console:
- OutputHey James Quick
So far, you’ve compiled one file directly. This is great, but in a real world project, you might want to customize how all files are compiled. For instance, you might want to have them be compiled to ES6 instead of ES5. To do this, you need to create a TypeScript configuration file.
To create a TypeScript configuration file, you can run the following command (similar to an npm init
):
- tsc --init
You will receive this output:
- Outputmessage TS6071: Successfully created a tsconfig.json file.
Open your new tsconfig.json
file and you’ll see lots of different options, most of which are commented out.
You might have noticed there is a setting called "target"
which is set to "es5"
. Change that setting to "es6"
.
With these changes made to tsconfig.json
, run tsc
in your terminal:
- tsc
Note: Unlike before, you are not specifying an input file. The official documentation points out: “When input files are specified on the command line, tsconfig.json
files are ignored.”
Now, open up the newly created JavaScript file:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function welcomePerson(person) {
console.log(`Hey ${person.firstName} ${person.lastName}`);
return `Hey ${person.firstName} ${person.lastName}`;
}
const james = {
firstName: "James",
lastName: "Quick"
};
welcomePerson(james);
Notice that the template literal string was left alone, proving that your TypeScript was compiled successfully to ES6.
Another thing you can change is where your JavaScript files are stored after being created. This setting can be specificed in "outDir"
.
Try deleting "outDir"
, and then start typing it in again. VS Code is providing you IntelliSense for which properties you can set in a TypeScript config file.
You can change your "outDir"
from the current directory to a dist
directory like so:
"outDir": "./dist"
After compiling again (tsc
), notice that your output JavaScript file is indeed located inside of a dist
directory.
You can use the cd
and ls
commands in your terminal to explore the contents of the dist
directory:
- cd dist
- ls
You will see your compiled JavaScript file in the new location:
- Outputapp.js
TypeScript has gained more and more popularity over the last couple of years. Here’s a couple of examples of how it is used in modern front-end frameworks.
Angular CLI projects come preconfigured with TypeScript. All of the configuration, linting, etc. is built in by default. Create an Angular CLI project and take a look around. This is a great way to see what TypeScript looks like in a real app.
Create React App doesn’t come with TypeScript by default, but with the latest version, it can be configured that way. If you’re interested in learning how to use TypeScript with Create React App, check out the Using Create React App v2 and TypeScript article.
Vue CLI projects can be configured to use TypeScript when creating a new project. For more details, you can check out the Vue Docs.
In this tutorial, you explored using TypeScript with VS Code. TypeScript allows you to generate higher quality JavaScript that can provide more confidence when shipping to production. As you can tell, VS Code is well equipped to help you write TypeScript, generate configurations, and so on.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
thanks. you helped me)))