Your First TypeScript Program
Now that your environment is set up, let us write, compile, and execute your first TypeScript program. We will also introduce a development tool called ts-node that streamlines this process.
1. Writing Your Code
First, make sure you have the directory structure set up as configured in your tsconfig.json.
Create a new folder named src in your project root, and then create a file named index.ts inside it:
mkdir src
touch src/index.tsOpen src/index.ts in your text editor and add the following code:
const username: string = "TypeScript Developer";
const birthYear: number = 2012;
function getAge(year: number): number {
const currentYear = new Date().getFullYear();
return currentYear - year;
}
console.log(`Hello, ${username}!`);
console.log(`TypeScript has been active for ${getAge(birthYear)} years.`);2. Compiling to JavaScript
To run this code, we first need to compile it to JavaScript.
In your terminal, run the compiler:
npx tscThis command reads your tsconfig.json file, locates your files inside the src folder, performs type checks, and writes the output files to your compiled build folder.
If you list the files in your project, you will see a new directory called dist containing the compiled JavaScript:
# Verify the output
cat dist/index.jsThe compiled dist/index.js file will look like this:
"use strict";
const username = "TypeScript Developer";
const birthYear = 2012;
function getAge(year) {
const currentYear = new Date().getFullYear();
return currentYear - year;
}
console.log(`Hello, ${username}!`);
console.log(`TypeScript has been active for ${getAge(birthYear)} years.`);Notice how the type annotations (: string, : number) have been removed by the compiler.
3. Running the Program
Now, execute the output JavaScript file using Node.js:
node dist/index.jsYou should see the output text printed in your terminal.
4. Faster Development with ts-node
Compiling code manually with tsc and running it with node every time you make a change can be slow.
To speed up development, we can use ts-node. This tool compiles TypeScript on-the-fly in memory and runs it directly, without writing JavaScript files to your hard drive.
Installing ts-node
Install it locally in your project:
npm install -g ts-nodeRunning Your TypeScript Code Directly
Now, run your TypeScript file in one command:
ts-node src/index.tsThis compiles and runs the program instantly, providing a much faster feedback loop during development.
5. Summary
- Write TypeScript code in files with the
.tsextension. - Use the command
npx tscto compile TypeScript into JavaScript. - Run the resulting JavaScript files using Node.js.
- Use
ts-nodeduring development to run TypeScript files directly without manual compilation steps.