TR | EN | DE | Our Site

JavaScript and TypeScript

 JavaScript and TypeScript

Overview of JavaScript and TypeScript

JavaScript is a dynamic, interpreted programming language widely used for web development. TypeScript is a superset of JavaScript that adds static typing, enabling developers to catch errors at compile time rather than runtime. This document will guide you through the key features and syntax of both languages.

Setting Up Your Environment

Before diving into coding, ensure you have the following installed:

  • Node.js: JavaScript runtime for executing code.
  • TypeScript: Install via npm:
    bash
    npm install -g typescript
  • Visual Studio Code: A popular code editor with TypeScript support.

Basic Syntax and Commands

1. Variables

In JavaScript and TypeScript, you can declare variables using letconst, or var.

  • let: Allows you to declare variables that can be reassigned.
  • const: Declares variables that cannot be reassigned (though the object they point to can still be modified).
  • var: Function-scoped or globally scoped; its use is generally discouraged in favor of let and const.

Example:

typescript
let mutableVariable: string = "Initial Value"; mutableVariable = "Updated Value"; // This is allowed const immutableVariable: number = 42; // immutableVariable = 50; // Error: Cannot assign to 'immutableVariable' because it is a constant. var globalVariable = "I am global"; // Avoid using 'var' in modern code

2. Functions

Functions in TypeScript can have typed parameters and return types, improving code clarity.Example:

typescript
function add(a: number, b: number): number { return a + b; } console.log(add(5, 10)); // Output: 15 // Optional Parameters function greetUser(name: string, greeting?: string): string { return `${greeting || "Hello"}, ${name}!`; } console.log(greetUser("Alice")); // Output: Hello, Alice! console.log(greetUser("Bob", "Welcome")); // Output: Welcome, Bob!

3. Interfaces

Interfaces are powerful for defining custom types and ensuring objects adhere to a specific structure.Example:

typescript
interface Product { id: number; name: string; price: number; } const product1: Product = { id: 1, name: "Laptop", price: 999.99, }; // Function using an interface function displayProduct(product: Product): void { console.log(`Product Name: ${product.name}, Price: $${product.price}`); } displayProduct(product1); // Output: Product Name: Laptop, Price: $999.99

4. Classes

TypeScript enhances JavaScript classes with features like access modifiers and interfaces.Example:

typescript
class Animal { protected name: string; constructor(name: string) { this.name = name; } public speak(): string { return `${this.name} makes a noise.`; } } class Dog extends Animal { public speak(): string { return `${this.name} barks.`; } } const dog = new Dog("Rex"); console.log(dog.speak()); // Output: Rex barks.

5. Generics

Generics allow you to create reusable components that work with any data type while maintaining type safety.Example:

typescript
function wrapInArray<T>(item: T): T[] { return [item]; } const numberArray = wrapInArray<number>(123); // [123] const stringArray = wrapInArray<string>("Hello"); // ["Hello"]

6. Working with Arrays and Tuples

TypeScript provides strong typing for arrays and tuples, allowing for more structured data handling.Arrays Example with Methods:

typescript
let fruits: string[] = ["Apple", "Banana", "Cherry"]; fruits.push("Orange"); console.log(fruits); // Output: ["Apple", "Banana", "Cherry", "Orange"] // Using map to transform data const fruitLengths = fruits.map(fruit => fruit.length); console.log(fruitLengths); // Output: [5, 6, 6, 6]

Tuples Example with Destructuring:

typescript
let userInfo: [string, number] = ["Alice", 30]; const [userName, userAge] = userInfo; console.log(`Name: ${userName}, Age: ${userAge}`); // Output: Name: Alice, Age: 30

7. Enums

Enums are a way of giving friendly names to sets of numeric values.Example with String Enums:

typescript
enum Color { Red = "RED", Green = "GREEN", Blue = "BLUE", } let favoriteColor: Color = Color.Green; console.log(favoriteColor); // Output: GREEN

8. Type Assertions

Type assertions allow you to specify a more specific type for a variable when you are confident about its type.Example with Non-null Assertion Operator (!):

typescript
let someValue: any = "This is a string"; let strLength1: number = (someValue as string).length; // Type assertion let strLength2: number = (<string>someValue).length; // Another syntax for type assertion console.log(strLength1); // Output will be the length of the string.

9. Error Handling in TypeScript

TypeScript helps catch errors at compile time, making your code more robust.Example of Type Safety in Function Parameters:

typescript
function multiply(a: number, b: number): number { return a * b; } // multiply(5, "10"); // Error! Argument of type 'string' is not assignable to parameter of type 'number'.

Compiling TypeScript to JavaScript

To compile your TypeScript code into JavaScript:

  1. Create a file named example.ts.
  2. Write your TypeScript code in it.
  3. Run the following command in your terminal:
    bash
    tsc example.ts
  4. This will generate an example.js file that you can run using Node.js:
    bash
    node example.js

An example program based on JavaScript and TypeScript

JavaScript Sample Program

Task Manager in JavaScript

javascript
// Task Manager using JavaScript class TaskManager { constructor() { this.tasks = []; } addTask(task) { this.tasks.push(task); console.log(`Task added: "${task}"`); } removeTask(task) { const index = this.tasks.indexOf(task); if (index > -1) { this.tasks.splice(index, 1); console.log(`Task removed: "${task}"`); } else { console.log(`Task not found: "${task}"`); } } displayTasks() { if (this.tasks.length === 0) { console.log("No tasks available."); return; } console.log("Current Tasks:"); this.tasks.forEach((task, index) => { console.log(`${index + 1}: ${task}`); }); } } // Usage const myTasks = new TaskManager(); myTasks.addTask("Learn JavaScript"); myTasks.addTask("Build a project"); myTasks.displayTasks(); myTasks.removeTask("Learn JavaScript"); myTasks.displayTasks();

How to Run the JavaScript Program

  1. Copy the code into a file named taskManager.js.
  2. Open your terminal and navigate to the directory where the file is saved.
  3. Run the program using Node.js:
    bash
    node taskManager.js

TypeScript Sample Program

Task Manager in TypeScript

typescript
// Task Manager using TypeScript class TaskManager { private tasks: string[]; constructor() { this.tasks = []; } public addTask(task: string): void { this.tasks.push(task); console.log(`Task added: "${task}"`); } public removeTask(task: string): void { const index = this.tasks.indexOf(task); if (index > -1) { this.tasks.splice(index, 1); console.log(`Task removed: "${task}"`); } else { console.log(`Task not found: "${task}"`); } } public displayTasks(): void { if (this.tasks.length === 0) { console.log("No tasks available."); return; } console.log("Current Tasks:"); this.tasks.forEach((task, index) => { console.log(`${index + 1}: ${task}`); }); } } // Usage const myTasks = new TaskManager(); myTasks.addTask("Learn TypeScript"); myTasks.addTask("Build a TypeScript project"); myTasks.displayTasks(); myTasks.removeTask("Learn TypeScript"); myTasks.displayTasks();

How to Run the TypeScript Program

  1. Copy the code into a file named taskManager.ts.
  2. Open your terminal and navigate to the directory where the file is saved.
  3. Compile the TypeScript code to JavaScript:
    bash
    tsc taskManager.ts
  4. This will generate a taskManager.js file.
  5. Run the compiled JavaScript program using Node.js:
    bash
    node taskManager.js

Expected Output

Both programs will produce similar output when executed:

text
Task added: "Learn JavaScript" Task added: "Build a project" Current Tasks: 1: Learn JavaScript 2: Build a project Task removed: "Learn JavaScript" Current Tasks: 1: Build a project

These sample programs illustrate how to manage tasks using classes in both JavaScript and TypeScript, showcasing their similarities and how TypeScript provides type safety. Happy coding!


Crow

physics, information technologies, author, educator

Post a Comment

Hello, share your thoughts with us.

Previous Post Next Post

İletişim Formu