[typescript]
  1. Getting Started with TypeScript
  2. TypeScript Data Types
  3. TypeScript Functions
  4. TypeScript Modules

Getting Started with TypeScript

TypeScript is a superset of JavaScript that compiles to plain JavaScript. It adds static types to the language, which can be checked by the TypeScript compiler to catch errors before runtime.

To get started with TypeScript, you first need to install it using npm:

npm install -g typescript

Once TypeScript is installed, you can create a .ts file, write your TypeScript code, and compile it to JavaScript using the tsc command:

tsc yourfile.ts

Now you can run the generated JavaScript file using Node.js.

TypeScript Data Types

TypeScript supports various data types such as number, string, boolean, array, tuple, enum, any, void, null, and undefined.

Here’s an example of how to declare variables with different data types in TypeScript:

let num: number = 10;
let str: string = "Hello, TypeScript!";
let isTrue: boolean = true;
let arr: number[] = [1, 2, 3, 4, 5];
let tuple: [string, number] = ["TypeScript", 2021];
let anyType: any = "I can be anything!";
let noValue: void = undefined;
let noValue2: null = null;

TypeScript Functions

In TypeScript, you can define functions with explicit parameter and return types:

function add(num1: number, num2: number): number {
    return num1 + num2;
}

let result: number = add(3, 5);

You can also use arrow functions:

let multiply = (num1: number, num2: number): number => {
    return num1 * num2;
}

TypeScript Modules

TypeScript supports modules and namespaces to organize code.

Here’s an example of exporting and importing modules:

// greeting.ts
export function greet(name: string): string {
    return `Hello, ${name}!`;
}

// app.ts
import { greet } from './greeting';
let message: string = greet("TypeScript");
console.log(message);

With these basics, you can start writing applications in TypeScript with confidence. Stay tuned for more advanced topics on TypeScript!