TypeScript Reference

Type-safe JavaScript with types, interfaces, generics, and type guards

Basic Types

Primitive Types

String, number, boolean, null, undefined

let name: string = "Alice";
let age: number = 30;
let isActive: boolean = true;
let value: null = null;
let notDefined: undefined = undefined;

Arrays

Type-safe arrays with two syntaxes

let numbers: number[] = [1, 2, 3];
let strings: Array<string> = ["a", "b", "c"];

Tuples

Fixed-length arrays with specific types

let tuple: [string, number] = ["age", 30];
let coords: [number, number, number] = [10, 20, 30];

Any & Unknown

Any disables type checking, unknown requires type checking

let anything: any = 42;
anything = "now a string"; // OK

let uncertain: unknown = 42;
// uncertain.toFixed(); // Error
if (typeof uncertain === "number") {
  uncertain.toFixed(); // OK
}

Interfaces

Basic Interface

Define object structure

interface User {
  id: number;
  name: string;
  email: string;
  age?: number; // Optional property
}

const user: User = {
  id: 1,
  name: "Alice",
  email: "alice@example.com"
};

Interface Extension

Inherit from other interfaces

interface Person {
  name: string;
  age: number;
}

interface Employee extends Person {
  employeeId: number;
  department: string;
}

const emp: Employee = {
  name: "Bob",
  age: 28,
  employeeId: 1001,
  department: "Engineering"
};

Function Interface

Define function signatures

interface MathOperation {
  (x: number, y: number): number;
}

const add: MathOperation = (x, y) => x + y;
const multiply: MathOperation = (x, y) => x * y;

Type Aliases

Union Types

Value can be one of several types

type ID = string | number;

function printId(id: ID) {
  if (typeof id === "string") {
    console.log(id.toUpperCase());
  } else {
    console.log(id.toFixed(0));
  }
}

Intersection Types

Combine multiple types

type HasName = { name: string };
type HasAge = { age: number };
type Person = HasName & HasAge;

const person: Person = {
  name: "Alice",
  age: 30
};

Literal Types

Exact values as types

type Direction = "north" | "south" | "east" | "west";
type Status = "success" | "error" | "pending";

function move(direction: Direction) {
  console.log(`Moving ${direction}`);
}

Generics

Generic Function

Functions that work with any type

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

const num = identity<number>(42);
const str = identity<string>("hello");
const auto = identity(true); // Type inferred

Generic Interface

Reusable interface with type parameter

interface Box<T> {
  value: T;
}

const numberBox: Box<number> = { value: 123 };
const stringBox: Box<string> = { value: "hello" };

Generic Constraints

Limit generic types with constraints

interface HasLength {
  length: number;
}

function logLength<T extends HasLength>(arg: T): void {
  console.log(arg.length);
}

logLength("hello"); // OK
logLength([1, 2, 3]); // OK
// logLength(123); // Error: number has no length

Type Guards

typeof Guard

Check primitive types

function processValue(value: string | number) {
  if (typeof value === "string") {
    return value.toUpperCase();
  } else {
    return value.toFixed(2);
  }
}

instanceof Guard

Check class instances

class Dog {
  bark() { console.log("Woof!"); }
}

class Cat {
  meow() { console.log("Meow!"); }
}

function makeSound(animal: Dog | Cat) {
  if (animal instanceof Dog) {
    animal.bark();
  } else {
    animal.meow();
  }
}

Custom Type Guard

Create your own type predicates

interface Fish {
  swim: () => void;
}

interface Bird {
  fly: () => void;
}

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

function move(pet: Fish | Bird) {
  if (isFish(pet)) {
    pet.swim();
  } else {
    pet.fly();
  }
}

Utility Types

Partial & Required

Make properties optional or required

interface User {
  name: string;
  age: number;
  email: string;
}

type PartialUser = Partial<User>; // All optional
type RequiredUser = Required<User>; // All required

const update: PartialUser = { age: 31 };

Pick & Omit

Select or exclude properties

interface User {
  id: number;
  name: string;
  email: string;
  password: string;
}

type PublicUser = Omit<User, "password">;
type UserCredentials = Pick<User, "email" | "password">;

Record

Create object type with specific keys

type Role = "admin" | "user" | "guest";

const permissions: Record<Role, string[]> = {
  admin: ["read", "write", "delete"],
  user: ["read", "write"],
  guest: ["read"]
};

Need SEO optimization tools?

Try Link Analyzer →