TypeScript Cheat Sheet

Here’s a basic TypeScript cheat sheet covering key aspects of the TypeScript programming language:

Hello World

console.log("Hello, TypeScript!");

Variable Declaration

let x: number = 10;
let name: string = "John";

Function Declaration

function addNumbers(a: number, b: number): number {
    return a + b;
}

Type Annotations

let age: number;
let isValid: boolean;
let message: string;
let values: number[] = [1, 2, 3];

Interfaces

interface Person {
    name: string;
    age: number;
}

let user: Person = {
    name: "Alice",
    age: 30,
};

Classes

class Car {
    private brand: string;

    constructor(brand: string) {
        this.brand = brand;
    }

    startEngine(): void {
        console.log(`${this.brand} engine started!`);
    }
}

const myCar = new Car("Toyota");
myCar.startEngine();

Enums

enum Color {
    Red,
    Green,
    Blue,
}

let selectedColor: Color = Color.Green;

Union Types

let value: number | string;
value = 10;
value = "Hello";

Generics

function identity<T>(arg: T): T {
    return arg;
}

let result: number = identity(42);
let output: string = identity("Hello");

Type Assertions

let value: any = "Hello, TypeScript!";
let length: number = (value as string).length;

Nullable Types

let data: string | null = fetchData();

Modules and Namespaces

// modules
import { ModuleA, ModuleB } from "./modules";

// namespaces
namespace MyNamespace {
    export function myFunction(): void {
        // Code
    }
}

TypeScript Configuration File (tsconfig.json)

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}

Compile TypeScript Code

tsc filename.ts

Run TypeScript Code

After compiling, run the generated JavaScript file using Node.js:

node filename.js

This cheat sheet covers some fundamental aspects of TypeScript. TypeScript extends JavaScript by adding static types, interfaces, and other features. For more detailed information, refer to the official TypeScript documentation