TypeScript

18 topics across 4 levels
TypeScript/Basic · Topic 1

Types, Interfaces & Type Aliases

Replace `any` with precise types for the data your tests read and assert on.

TypeScript infers types automatically from literals and return values, but for anything crossing a boundary — API responses, function parameters, fixture data — write the type down explicitly so a typo becomes a compile error instead of a 3am flaky-test mystery.

interface describes the shape of an object and can be extended (interface Admin extends User) or merged across multiple declarations. type aliases can do everything an interface can for object shapes, plus unions, tuples, and other compositions interfaces can't express. Default to interface for public object shapes, type for everything else.

Real-world use case

Typing the JSON body a test's request.get() call returns, so response.roles.include('admin') — a typo of .includes — fails at compile time instead of silently returning undefined at runtime.

Example code

src/types/api.ts
interface ApiUser {
  id: number;
  username: string;
  email: string;
  roles: string[];
  isActive?: boolean; // optional — may be absent on the wire
}

type Role = "admin" | "editor" | "viewer";

function describeUser(user: ApiUser): string {
  return `${user.username} <${user.email}>`;
}
Type an API response

Define an interface ApiUser (id: number, username: string, email: string, roles: string[]) matching the JSON below, then implement isActiveAdmin.

Loading editor…
Execution isn't wired up yet — this editor is for writing/reviewing, not running.