← Technology Archive

Historical archive

TypeScript Basics: Types, Interfaces, Classes, and Functions

Introductory TypeScript notes covering primitive types, arrays, tuples, enums, interfaces, classes, access control, inheritance, and function types.

Declaring variables in TypeScript

TypeScript lets us declare a variable’s type before using it.

Primitive types

let text: string = 'Hello World';

let decimal: number = 123;
let binary: number = 0b0101;
let octal: number = 0o7777;
let hexadecimal: number = 0xffff;
let large: bigint = 100n;

let enabled: boolean = false;
let token: symbol = Symbol();

Object types

Arrays can use either T[] or Array<T> syntax:

let words: string[] = ['hello', 'world'];
let moreWords: Array<string> = ['hello', 'world'];

A tuple fixes the number and types of its elements:

let pair: [string, number] = ['hello', 1];

An enum defines a named set of values:

enum Sex {
  Male,
  Female,
}

let value: Sex = Sex.Male;

Interfaces describe an object’s required shape:

interface Hero {
  name: string;
  readonly id: number;
  attack(): void;
}

An interface can:

  1. Declare properties and method signatures without implementations.
  2. Extend another interface.
  3. Declare read-only properties.

Classes

TypeScript classes support:

  1. Instance properties and methods.
  2. Static properties and methods.
  3. Constructors and instantiation with new.
  4. Access modifiers such as public, protected, and private.
  5. Class inheritance.
  6. Interface implementation.
  7. Parameter properties, such as constructor(private name: string) {}.
  8. Arrow-function fields that preserve lexical this.
  9. Method overriding and overload signatures.

Function types

Function parameters and return values can be typed explicitly:

function add(left: number, right: number): number {
  return left + right;
}

const format: (value: number) => string = (value) => String(value);

These examples form a starting point; modern TypeScript also adds unions, intersections, generics, conditional types, type inference, and many more tools for modeling application data.