Skip to content

Typescript

https://www.typescriptlang.org/

TypeScript is an open-source programming language developed by Microsoft. It is a superset of JavaScript, which means that any valid JavaScript code is also valid TypeScript code. However, TypeScript adds static typing and other features to help developers catch errors during development and improve the maintainability of code, especially in large-scale projects.

Key features and aspects of TypeScript include:

  1. Static Typing: One of the main features of TypeScript is static typing. Developers can define types for variables, function parameters, and return types, allowing the TypeScript compiler to catch type-related errors during development rather than at runtime.

    typescript
    function greet(name: string): string {
      return `Hello, ${name}!`;
    }
  2. Interfaces and Type Declarations: TypeScript allows developers to define custom types using interfaces or type declarations. This promotes code consistency and documentation.

    typescript
    interface Person {
      name: string;
      age: number;
    }
    
    const user: Person = { name: 'John', age: 25 };
  3. Type Inference: TypeScript's type inference feature automatically deduces types based on the assigned values, reducing the need for explicit type annotations in many cases.

    typescript
    let message = 'Hello, TypeScript!'; // TypeScript infers the type as string
  4. Enums: Enums allow developers to define named constant values, providing a way to represent a set of related values in a more readable and maintainable manner.

    typescript
    enum Color {
      Red,
      Green,
      Blue,
    }
    
    let favoriteColor: Color = Color.Green;
  5. Generics: TypeScript supports generics, enabling the creation of flexible and reusable functions and data structures that can work with a variety of types.

    typescript
    function identity<T>(arg: T): T {
      return arg;
    }
    
    let result = identity<string>('Hello, TypeScript!');
  6. Decorators: TypeScript supports decorators, which are a way to modify or extend the behavior of classes or class members. Decorators are commonly used in frameworks like Angular for metadata annotations.

    typescript
    @log
    class Example {
      // Class implementation
    }
    
    function log(target: any) {
      console.log(`Class logged: ${target}`);
    }
  7. Module System: TypeScript uses the ECMAScript module system, allowing developers to organize code into modular and reusable components. It supports both CommonJS and ES6 module syntax.

    typescript
    // Importing a module
    import { myFunction } from './myModule';
    
    // Exporting a module
    export function myFunction() {
      // Module implementation
    }
  8. Compatibility with JavaScript: TypeScript code can coexist with existing JavaScript code, allowing developers to gradually adopt TypeScript in their projects without the need for a full rewrite.

To use TypeScript, developers typically install it using npm or yarn, create a tsconfig.json configuration file, and then compile TypeScript code to JavaScript using the TypeScript compiler (tsc). Many modern web development frameworks, including Angular and React, also support TypeScript out of the box.

Examples

1. Static Typing:

typescript
// Static typing for variables
let age: number = 25;
let name: string = "John";
let isAdult: boolean = true;

// Static typing for arrays
let numbers: number[] = [1, 2, 3];
let names: string[] = ["Alice", "Bob"];

// Static typing for functions
function add(x: number, y: number): number {
  return x + y;
}

2. Interfaces:

typescript
// Using interfaces to define object shapes
interface Person {
  name: string;
  age: number;
}

function greet(person: Person): string {
  return `Hello, ${person.name}! You are ${person.age} years old.`;
}

const user: Person = { name: "Alice", age: 30 };
console.log(greet(user));

3. Classes and Inheritance:

typescript
// Using classes and inheritance
class Animal {
  constructor(public name: string) {}

  makeSound(): string {
    return "Some generic sound";
  }
}

class Dog extends Animal {
  makeSound(): string {
    return "Woof, woof!";
  }
}

const myDog = new Dog("Buddy");
console.log(myDog.name); // Buddy
console.log(myDog.makeSound()); // Woof, woof!

4. Generics:

typescript
// Using generics for flexible functions
function identity<T>(value: T): T {
  return value;
}

let result1: number = identity(42);
let result2: string = identity("hello");

5. Enums:

typescript
// Using enums for named constant values
enum Color {
  Red,
  Green,
  Blue,
}

let selectedColor: Color = Color.Green;
console.log(selectedColor); // 1 (index of Green in the enum)

6. Union and Intersection Types:

typescript
// Using union and intersection types
type NumberOrString = number | string;
type PersonInfo = { name: string } & { age: number };

let value: NumberOrString = 42;
let personInfo: PersonInfo = { name: "Alice", age: 25 };

7. Type Assertions:

typescript
// Using type assertions
let value: any = "hello";
let length: number = (value as string).length;

8. Null and Undefined Handling:

typescript
// Using strict null-checking
let username: string | null = getUser() ?? "DefaultUser";

function getUser(): string | null {
  // Simulating a function that may return null
  return Math.random() > 0.5 ? "JohnDoe" : null;
}

9. Decorators:

typescript
// Using decorators
function log(target: any, key: string): void {
  console.log(`Method ${key} is called.`);
}

class Example {
  @log
  greet(): void {
    console.log("Hello!");
  }
}

const instance = new Example();
instance.greet(); // This will trigger the log decorator

These examples showcase the use of TypeScript features in various contexts. TypeScript provides a rich set of tools to enhance JavaScript development, making code more readable, maintainable, and less error-prone.

Courses

Understanding Typescript
Typescript: The complete developer's guide
Mastering Typescript - 2024 Edition

Released under the MIT License.