TypeScript

JavaScript with syntax for types

TypeScript Overview

TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale. It adds optional static typing to JavaScript, which helps catch errors early through a type system.

Paradigm

Multi-paradigm: functional, generic, imperative, object-oriented

Designed by

Microsoft (Anders Hejlsberg)

First appeared

October 1, 2012

Stable release

5.1 (May 2023)

Key Features

Common Use Cases

Large-Scale Applications

Type safety helps manage complexity in large codebases.

Frontend Frameworks

Used with React, Angular, and Vue for type-safe UIs.

Node.js Backends

Type-safe server-side development.

Library Development

Better documentation and usage patterns with types.

Example Code

// TypeScript example demonstrating types and features
interface Person {
    name: string;
    age: number;
    greet(): string;
}

class Employee implements Person {
    constructor(
        public name: string,
        public age: number,
        private salary: number
    ) {}

    greet() {
        return `Hello, my name is ${this.name}`;
    }

    getSalary() {
        return this.salary;
    }
}

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

// Async/await with types
async function fetchData<T>(url: string): Promise<T> {
    const response = await fetch(url);
    return await response.json() as T;
}

// Using the examples
const alice = new Employee("Alice", 30, 50000);
console.log(alice.greet());

const result = identity<string>("TypeScript is awesome");
console.log(result);

type User = { id: number; name: string };
fetchData<User[]>("https://api.example.com/users")
    .then(users => console.log(users))
    .catch(error => console.error(error));

// Tuple type
let coordinates: [number, number] = [10, 20];
console.log(coordinates);

Learning Resources