DEV Community

Cover image for Typescript

Typescript

TypeScript is a superset of JavaScript that adds static typing to help catch errors during development and make code more predictable. Below are the main syntax elements and concepts you need to understand in TypeScript, along with examples.

Type Annotations

TypeScript allows you to explicitly define the types of variables, function parameters, and return values.

// Variables with types
let isDone: boolean = true;
let count: number = 42;
let name: string = "Irena";

// Arrays
let numbers: number[] = [1, 2, 3];
let names: string[] = ['Alice', 'Bob'];

// Tuple (fixed size and type array)
let person: [string, number] = ['Irena', 30];

// Any (disables type checking)
let unknownValue: any = 'hello';
unknownValue = 42;  // valid
Enter fullscreen mode Exit fullscreen mode

Functions

Functions in TypeScript can have type annotations for parameters and return values. Optional and default parameters are also supported

// Function with typed parameters and return value
function add(a: number, b: number): number {
  return a + b;
}

// Optional parameter
function greet(name: string, age?: number): string {
  return age ? `Hello, ${name}. You are ${age}.` : `Hello, ${name}.`;
}

// Default parameter
function log(message: string = "Default message"): void {
  console.log(message);
}
Enter fullscreen mode Exit fullscreen mode

###Interfaces
Interfaces define the shape of objects, ensuring that objects adhere to a particular structure.

interface Person {
  name: string;
  age: number;
  greet(): string;
}

const person1: Person = {
  name: 'Irena',
  age: 30,
  greet: () => `Hello, my name is ${person1.name}`
};
Enter fullscreen mode Exit fullscreen mode

Classes

TypeScript allows you to create classes with properties and methods. It supports object-oriented features like inheritance, access modifiers (public, private, protected), and abstract classes.

class Animal {
  // Access modifiers: public, private, protected
  public name: string;
  private age: number;

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

  public speak(): string {
    return `The animal ${this.name} makes a sound.`;
  }

  private getAge(): number {
    return this.age;
  }
}

// Inheritance
class Dog extends Animal {
  constructor(name: string, age: number) {
    super(name, age);
  }

  public speak(): string {
    return `The dog ${this.name} barks.`;
  }
}

const dog = new Dog("Buddy", 3);
console.log(dog.speak());
Enter fullscreen mode Exit fullscreen mode

Enums

Enums are used to define a set of named constants.

enum Direction {
  Up,
  Down,
  Left,
  Right
}

let move: Direction = Direction.Up;
Enter fullscreen mode Exit fullscreen mode

Generics

Generics allow you to create reusable components that work with any type, providing flexibility and type safety.

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

let result = identity<string>("hello");  // 'hello'
let numberResult = identity<number>(42);  // 42

// Generic interfaces
interface Box<T> {
  content: T;
}

const stringBox: Box<string> = { content: "A string" };
const numberBox: Box<number> = { content: 100 };
Enter fullscreen mode Exit fullscreen mode

Union & Intersection Types

Union types allow a variable to be one of several types, while intersection types combine multiple types into one.

// Union Type (value can be string or number)
let value: string | number = "Hello";
value = 42;

// Intersection Type (combine multiple types)
interface ErrorHandling {
  success: boolean;
  error?: { message: string };
}

interface Data {
  data: { name: string };
}

type ApiResponse = ErrorHandling & Data;

const response: ApiResponse = {
  success: true,
  data: { name: "Irena" }
};
Enter fullscreen mode Exit fullscreen mode

Type Aliases

Type aliases allow you to give a name to a type, which can be a primitive, union, or a more complex structure.

type StringOrNumber = string | number;

let result1: StringOrNumber = "Hello";
let result2: StringOrNumber = 42;

Type Assertions
Type assertions are used to tell the compiler to treat a value as a specific type

let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Enter fullscreen mode Exit fullscreen mode

Modules

TypeScript uses the ES6 module syntax to organize code. You can export and import modules.

// person.ts
export interface Person {
  name: string;
  age: number;
}

// main.ts
import { Person } from './person';

const person: Person = { name: 'Irena', age: 30 };
Enter fullscreen mode Exit fullscreen mode

Key Takeaways:

Type Annotations: Specify the type of variables, function parameters, and return values.
Interfaces and Types: Define the structure of objects.
Generics: Allow functions and classes to work with any type.
Access Modifiers: Control visibility of class properties and methods (public, private, protected).
Modules: Organize your code by exporting and importing across different files.
TypeScript helps prevent runtime errors by providing early checks, making the development process more robust!

Top comments (0)