CodeToLive

Introduction to TypeScript

TypeScript is a statically typed superset of JavaScript developed by Microsoft. It adds optional static typing, classes, interfaces, and other features to JavaScript, making it suitable for large-scale applications. TypeScript code is transpiled into plain JavaScript, ensuring compatibility with all JavaScript environments.

Why Use TypeScript?

Setting Up TypeScript

To use TypeScript, you need to install it globally via npm:


npm install -g typescript
      

Create a TypeScript file (e.g., app.ts) and compile it to JavaScript using the TypeScript compiler:


tsc app.ts
      

This will generate a corresponding app.js file that can be executed in any JavaScript environment.

TypeScript Configuration

TypeScript uses a configuration file (tsconfig.json) to specify compiler options and project settings. You can generate a default configuration file using:


tsc --init
      

This creates a tsconfig.json file with default settings, which you can customize as needed.

Example: Hello World in TypeScript


// TypeScript Hello World Program
let message: string = "Hello, World!";
console.log(message);
      

This code declares a variable message of type string and logs it to the console. The TypeScript compiler will generate equivalent JavaScript code:


// Compiled JavaScript Code
var message = "Hello, World!";
console.log(message);
      

Basic Types in TypeScript

TypeScript introduces several basic types, including:


// Example of Basic Types
let name: string = "Alice";
let age: number = 30;
let isActive: boolean = true;
let scores: number[] = [95, 89, 78];
let user: [string, number] = ["Alice", 30]; // Tuple
enum Color { Red, Green, Blue };
let backgroundColor: Color = Color.Blue;
      

Type Inference

TypeScript can infer types automatically based on the assigned value. This reduces the need for explicit type annotations.


let message = "Hello, TypeScript!"; // TypeScript infers `message` as `string`
let count = 10; // TypeScript infers `count` as `number`
      

Next Steps

Now that you have a basic understanding of TypeScript, you can explore more advanced topics such as variables, data types, functions, and classes.

Next: Variables and Data Types