TypeScript extends JavaScript by adding static types. This makes your code easier to understand and prevents common errors. This article gives you a quick introduction to TypeScript. You will learn enough to start using it in your projects.
Setting Up Your Environment
Before you begin, you need a TypeScript development environment. You’ll need Node.js and npm (Node Package Manager) installed. You can download them from the Node.js website.
Once you have Node.js and npm, install TypeScript globally:
npm install -g typescript
This command installs the TypeScript compiler (tsc). You can then compile TypeScript files into JavaScript.
JavaScript Runtimes
The way you run TypeScript code depends on your JavaScript runtime environment. These environments include Node.js, Deno, and Bun.
-
Node.js: Compile your TypeScript code to JavaScript using
tsc. Then, run the JavaScript file withnode:tsc yourfile.ts node yourfile.js -
Deno: Deno supports TypeScript natively. You can run TypeScript files directly:
deno run yourfile.ts -
Bun: Bun also supports TypeScript natively. Run TypeScript files using:
bun run yourfile.ts
Variables and Data Types
Variables store data. TypeScript adds static typing to JavaScript. You can specify the type of a variable.
let name: string = "Alice";
let age: number = 30;
let price: number = 9.99;
let isEmployed: boolean = true;
If you don’t specify a type, TypeScript can often infer it:
let score = 0; // TypeScript infers that 'score' is a number
TypeScript includes basic types like string, number, boolean, null, and undefined. It also supports more complex types such as arrays, tuples, and objects.
Operators
TypeScript supports standard JavaScript operators. These include arithmetic operators (+, -, *, /, %), comparison operators (==, !=, >, <, >=, <=), and logical operators (&&, ||, !).
let x = 10;
let y = 5;
let sum = x + y;
let greater = x > y;
let bothTrue = true && true;
Control Flow
Control flow statements control the order in which code runs.
If Statements
if statements run code based on a condition.
let number = 7;
if (number > 5) {
console.log("Number is greater than 5");
}
You can add an else block for alternative code:
let number = 3;
if (number > 5) {
console.log("Number is greater than 5");
} else {
console.log("Number is 5 or less");
}
Switch Statements
switch statements handle multiple conditions.
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Another day");
}
Loops
Loops repeat a block of code.
For Loops
for loops iterate over a range or collection.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
This loop prints numbers from 1 to 5.
While Loops
while loops continue as long as a condition is true.
let count = 0;
while (count < 3) {
console.log(count);
count++;
}
Functions
Functions group reusable code. They accept input and can return output. TypeScript lets you specify the types of function parameters and return values. TypeScript also supports asynchronous functions, which are useful for handling operations that take time, like fetching data from a server.
async function fetchData(): Promise<string> {
// Simulate fetching data
return new Promise(resolve => {
setTimeout(() => {
resolve("Data fetched!");
}, 1000);
});
}
async function greet(name: string): Promise<string> {
return `Hello, ${name}!`;
}
let message = greet("Bob");
console.log(message);
This function takes a string as input and returns a greeting message.
Basic Data Structures
TypeScript works with standard JavaScript data structures.
Arrays
Arrays store collections of items.
let numbers: number[] = [1, 2, 3, 4, 5];
console.log(numbers[0]); // Accessing the first element
Objects
Objects store key-value pairs. You can define the structure of an object using interfaces or types.
interface Person {
name: string;
age: number;
}
let person: Person = {
name: "Alice",
age: 30
};
console.log(person.name); // Accessing the name of the person
Destructuring provides a convenient way to extract values from objects. Instead of accessing properties individually, you can unpack them into separate variables.
interface Person {
name: string;
age: number;
}
let person: Person = {
name: "Alice",
age: 30
};
const { name, age } = person;
console.log(name);
console.log(age);
This makes the code more readable and concise.
Conclusion
This article covered the basics of TypeScript. You should now understand variables, operators, control flow, functions, and data structures. Keep practicing and explore the language further to build more complex applications. The official TypeScript documentation provides more information.