Getting Started with TypeScript

Introduction to TypeScript and setting up your development environment

Getting Started with TypeScript

TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale.

What is TypeScript?

TypeScript is a superset of JavaScript that adds static type definitions. It was developed by Microsoft and has gained widespread adoption in the JavaScript community.

Why Use TypeScript?

  1. Type Safety: Catch errors at compile time rather than runtime
  2. Better IDE Support: Enhanced autocomplete, refactoring, and navigation
  3. Self-Documenting Code: Types serve as inline documentation
  4. Easier Refactoring: Confident code changes with type checking
  5. Better Team Collaboration: Clear interfaces and contracts

Installation

You can install TypeScript globally or as a project dependency:

# Global installation
npm install -g typescript

# Project dependency
npm install --save-dev typescript

Your First TypeScript File

Create a file called hello.ts:

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

const message = greet("World");
console.log(message);

Compiling TypeScript

Compile your TypeScript file to JavaScript:

tsc hello.ts

This creates a hello.js file with the compiled JavaScript code.

TypeScript Configuration

Create a tsconfig.json file to configure the TypeScript compiler:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

Basic Types

TypeScript includes several basic types:

// Primitives
let isDone: boolean = false;
let decimal: number = 6;
let color: string = "blue";

// Arrays
let list: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];

// Tuple
let x: [string, number] = ["hello", 10];

// Enum
enum Color {
  Red,
  Green,
  Blue,
}
let c: Color = Color.Green;

// Any (avoid when possible)
let notSure: any = 4;

// Void
function warnUser(): void {
  console.log("This is my warning message");
}

Development Workflow

  1. Write TypeScript code with type annotations
  2. Use tsc --watch for automatic compilation
  3. Run the compiled JavaScript with Node.js
  4. Use your IDE's TypeScript support for real-time error checking

Next Steps

In the following lessons, we'll dive deeper into:

  • Interfaces and type aliases
  • Classes and inheritance
  • Generics
  • Advanced types
  • Working with external libraries

Let's continue building your TypeScript knowledge!