Your First TypeScript Program: A Step-by-Step Guide
Learn how to write, compile, and run your initial TypeScript program. Discover the process of transforming TypeScript code into executable JavaScript, and explore the benefits of using type annotations for improved code quality.
Compiling and Running Your First TypeScript Program
- Write TypeScript Code:
- Create a
.ts
file (e.g.,add.ts
). - Define functions, variables, and other TypeScript constructs.
- Use type annotations for better code clarity and error prevention.
- Create a
- Compile to JavaScript:
- Open a terminal or command prompt.
- Navigate to the directory containing your TypeScript file.
- Use the
tsc
command to compile:Compile TypeScript
tsc add.ts
- This creates a corresponding
.js
file (e.g.,add.js
).
- Include in HTML:
- Create an HTML file (e.g.,
index.html
). - Include the generated JavaScript file using a
<script>
tag.
- Create an HTML file (e.g.,
- Run the HTML file:
- Open the HTML file in a web browser.
- The JavaScript code will execute, and the output will be displayed in the browser's console.
Example
add.ts:
TypeScript Code
function addNumbers(a: number, b: number) {
return a + b;
}
var sum: number = addNumbers(10, 15);
console.log('Sum of the two numbers is: ' + sum);
index.html:
HTML Code
<!DOCTYPE html>
<html>
<head>
<title>TypeScript Example</title>
</head>
<body>
<script src="add.js"></script>
</body>
</html>
Key Points
- TypeScript is a superset of JavaScript, meaning valid JavaScript code is also valid TypeScript.
- The
tsc
compiler translates TypeScript code into JavaScript that can be run in browsers or Node.js environments. - Type annotations enhance code readability and help prevent runtime errors.
- IDEs often provide features to simplify the compilation process and debugging.
Additional Tips
- Use a code editor or IDE with TypeScript support for a better development experience.
- Consider using a build tool like webpack or Parcel for larger projects.
- Explore TypeScript's rich feature set, including interfaces, classes, modules, and more.
By following these steps and understanding the core concepts, you can effectively create and run TypeScript applications.