Basics
TS Running Code
Running TypeScript Code
TypeScript code runs via tsc compilation to JavaScript with ts-node for scripts.
Introduction to Running TypeScript Code
TypeScript is a powerful language that builds on JavaScript by adding static types. To execute TypeScript code, it must first be compiled into JavaScript. This can be achieved using the TypeScript compiler tsc
or by using ts-node
for running scripts directly.
Compiling TypeScript with tsc
The TypeScript Compiler (tsc) is the most common way to convert TypeScript code to JavaScript. This process involves compiling the TypeScript files into JavaScript files, which can then be executed in any JavaScript environment such as browsers or Node.js.
To compile TypeScript code using tsc
, follow these steps:
- Ensure TypeScript is installed in your project. You can do this by running
npm install -g typescript
. - Compile the TypeScript file by running
tsc filename.ts
. This will generate afilename.js
file.
Here’s a simple example:
After running tsc example.ts
, a new file example.js
will be created with the following content:
Running TypeScript with ts-node
While tsc
is great for compiling TypeScript code, ts-node
offers a more efficient way to run TypeScript files directly without compiling them to JavaScript first. This tool is particularly useful for running scripts or development purposes.
To use ts-node
, follow these steps:
- Install
ts-node
globally by runningnpm install -g ts-node
. - Run your TypeScript file directly with
ts-node filename.ts
.
Using the same example, you can execute the example.ts
file directly with:
This command will output Hello, TypeScript!
directly to the console, without generating a separate JavaScript file.
Conclusion
Understanding how to run TypeScript code is essential for any developer working with this language. Whether you choose to compile TypeScript files using tsc
or run them directly with ts-node
, both methods provide flexibility based on your development needs. In the next post, we'll dive into the syntax of TypeScript to further enhance your coding skills.
Basics
- Previous
- Installation
- Next
- Syntax