Language: EN

cheatsheet-typescript

TypeScript Cheatsheet

TypeScript is a typed superset of JavaScript that adds static types and other object-oriented programming features.

Introduction

Installing TypeScript

To install TypeScript globally:

npm install -g typescript

Compiling a TypeScript file

Compile a .ts file to .js.

tsc file.ts

Starting a TypeScript project

Initialize a project with a tsconfig.json file to configure the compiler.

tsc --init

Types

Defining basic types

TypeScript includes a series of primitive types: number, string, boolean, null, undefined, any.

let age: number = 25;
let name: string = "Luis";
let isStudent: boolean = true;

Arrays

Arrays are typed by indicating the type followed by [].

let numbers: number[] = [1, 2, 3, 4];
let names: string[] = ["Luis", "María"];

Tuples

Tuples allow defining arrays with a fixed number of elements of specific types.

let person: [string, number] = ["Luis", 25];

Enums

Enums allow defining a set of named constants.

enum Color { Red, Green, Blue }
let favoriteColor: Color = Color.Blue;

any type

any disables type checking, allowing any value.

let value: any = 5;
value = "text";

Union Types

Allows defining variables that can be of multiple types.

let result: string | number = "Approved";
result = 85;

Null and Undefined Types

let value: string | null | undefined;

Intersection Types

Intersection types combine multiple types into one.

interface WithName {
  name: string;
}

interface WithAge {
  age: number;
}

type CompletePerson = WithName & WithAge;

Literal Types

Literal types can be created with specific values.

type Colors = "Red" | "Green" | "Blue";
let color: Colors = "Red";

Type Assertions

Type assertions allow telling the compiler to treat a value as a specific type.

let value: any = "Hello world";
let length: number = (value as string).length;

Functions

Defining functions with types

Functions in TypeScript can define types for parameters and return values.

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

Optional parameters and default values

Optional parameters can be defined using ? and default values.

function greet(name: string, greeting?: string): string {
  return `${greeting || "Hello"}, ${name}`;
}

Functions with void type

A function that does not return anything uses the void type.

function logMessage(message: string): void {
  console.log(message);
}

Anonymous functions (arrow functions)

Arrow functions with types.

const multiply = (x: number, y: number): number => x * y;

Interfaces

Defining interfaces

An interface allows defining the structure of an object.

interface Person {
  name: string;
  age: number;
  isStudent?: boolean;
}

const person1: Person = {
  name: "Luis",
  age: 25
};

Interfaces for functions

Interfaces can also define the structure of a function.

interface Sum {
  (a: number, b: number): number;
}

let mySum: Sum = (x, y) => x + y;

Extending interfaces

Interfaces can be extended to inherit properties from others.

interface Student extends Person {
  enrollment: number;
}

Classes and Object-Oriented Programming

Defining classes

TypeScript supports object-oriented programming with classes, which include properties and methods.

class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

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

Access modifiers

The public, private, and protected modifiers control the visibility of properties and methods.

class Student {
  public name: string;
  private enrollment: number;

  constructor(name: string, enrollment: number) {
    this.name = name;
    this.enrollment = enrollment;
  }

  getEnrollment(): number {
    return this.enrollment;
  }
}

Inheritance

Classes can inherit from other classes using extends.

class Teacher extends Person {
  specialty: string;

  constructor(name: string, age: number, specialty: string) {
    super(name, age);
    this.specialty = specialty;
  }
}

Abstract classes

Abstract classes cannot be instantiated directly; they can only be inherited.

abstract class Animal {
  abstract sound(): void;
}

class Dog extends Animal {
  sound() {
    console.log("Woof");
  }
}

Generics

Defining Generics

Generics allow writing reusable code that works with multiple data types.

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

Generics in classes

Generics can be used in classes to allow different types of properties.

class Box<T> {
  content: T;
  constructor(content: T) {
    this.content = content;
  }

  getContent(): T {
    return this.content;
  }
}

const numberBox = new Box<number>(123);

Modules and Namespaces

Importing and exporting modules

Code can be split into multiple files and use export and import to share code between them.

// fileA.ts
export const PI = 3.14;

// fileB.ts
import { PI } from './fileA';
console.log(PI);

Namespaces

Namespaces allow grouping related code under a single name, useful for avoiding name conflicts.

namespace Geometry {
  export function circleArea(radius: number): number {
    return Math.PI * radius * radius;
  }
}

console.log(Geometry.circleArea(5));

Decorators

Class decorators

A decorator is a special function that can modify the behavior of a class or its members.

function log(target: any) {
  console.log(`Decorated class: ${target.name}`);
}

@log
class MyClass {
  constructor() {
    console.log("Instance created");
  }
}

Method decorators

Method decorators allow intercepting the execution of methods.

function logCall(target: any, key: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;
  descriptor.value = function (...args: any[]) {
    console.log(`Method called: ${key}`);
    return originalMethod.apply(this, args);
  };
}

class Calculator {
  @logCall
  add(a: number, b: number): number {
    return a + b;
  }
}

Handling Promises and Asynchrony

async/await functions

TypeScript supports handling promises using async and await for cleaner code.

async function getData(): Promise<string> {
  return new Promise((resolve) => {
    setTimeout(() => resolve("Data obtained"), 1000);
  });
}

async function displayData() {
  const data = await getData();
  console.log(data);
}

Error handling in async/await

Error handling in asynchronous functions is done with try/catch blocks.

async function getDataWithError() {
  try {
    const data = await getData();
    console.log(data);
  } catch (error) {
    console.error("Error obtaining data", error);
  }
}

Configuring tsconfig.json

Important parameters in tsconfig.json

The tsconfig.json file allows configuring TypeScript compilation options.

{
  "compilerOptions": {
    "target": "es6",              // ECMAScript output version
    "module": "commonjs",          // Module system
    "strict": true,                // Enable all strict type-checking options
    "esModuleInterop": true,       // Enables emit interoperability between CommonJS and ES Modules
    "outDir": "./dist",            // Output directory
    "rootDir": "./src"             // Entry directory
  },
  "include": ["src/**/*"],         // Files included in the compilation
  "exclude": ["node_modules"]      // Files excluded from the compilation
}