Skip to main content

Basic Syntax & Compilation in TypeScript

In this tutorial, we will explore the basic syntax of TypeScript and learn how to compile TypeScript code into JavaScript. Understanding these fundamentals will lay the foundation for more advanced TypeScript concepts.

TypeScript Syntax

TypeScript's syntax is a superset of JavaScript, meaning that valid JavaScript code is also valid TypeScript code. However, TypeScript introduces additional syntax elements for defining types, classes, and interfaces. Let's take a look at some common TypeScript syntax elements:

1. Variables and Type Annotations

In TypeScript, you can declare variables using let or const and add optional type annotations to specify the variable's data type:

TypeScript
let age: number = 25;
const message: string = 'Hello, TypeScript!';

2. Functions

Functions in TypeScript can include type annotations for their parameters and return values:

TypeScript
function greet(name: string): string {
return `Hello, ${name}!`;
}

3. Classes and Interfaces

TypeScript supports classes and interfaces for object-oriented programming:

TypeScript
interface Person {
firstName: string;
lastName: string;
}

class Employee implements Person {
firstName: string;
lastName: string;

constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}

getFullName(): string {
return `${this.firstName} ${this.lastName}`;
}
}

These are just a few examples of TypeScript's syntax. In the next tutorials, we will dive deeper into each topic and learn more about TypeScript's features.

Compiling TypeScript Code

To compile TypeScript code into JavaScript, you need to use the tsc (TypeScript Compiler) command. Create a TypeScript file named hello.ts with the following content:

hello.ts
let message: string = 'Hello, TypeScript!';
console.log(message);

To compile the hello.ts file into JavaScript, run the following command:

tsc hello.ts

This command will generate a hello.js file with the following JavaScript code:

hello.js
var message = 'Hello, TypeScript!';
console.log(message);

By default, tsc compiles TypeScript code into ECMAScript 3 (ES3) JavaScript. You can target different versions of JavaScript by providing the --target flag followed by the desired version:

tsc hello.ts --target ES2015

This command will generate JavaScript code compatible with ECMAScript 2015 (ES6).

Conclusion

In this tutorial, we have covered the basic syntax and compilation process in TypeScript. With a solid understanding of TypeScript's syntax and how to compile your code into JavaScript, you are ready to explore more advanced concepts and features in the upcoming tutorials.