06 - Interfaces, Types, and Unions
📋 Jump to Takeaways🎁 Java has interface. Go has interface. TypeScript has interface AND type — and they're not the same thing. Knowing when to use which one (and why unions beat enums) is what separates TypeScript novices from engineers who write idiomatic code.
TypeScript gives you two ways to define types: interface and type alias. They overlap a lot, but each has strengths. Then there are union types and intersections, which let you compose types in ways Go and Java can't touch.
Interfaces
An interface defines the shape of an object. Properties, methods, optional fields.
interface User {
id: number;
name: string;
email: string;
role?: string; // optional
}
const user: User = {
id: 1,
name: "Alice",
email: "[email protected]",
};
// user.role is string | undefinedExtending Interfaces
Interfaces can extend other interfaces. Same idea as embedding structs in Go.
interface Timestamped {
createdAt: Date;
updatedAt: Date;
}
interface Post extends Timestamped {
id: number;
title: string;
body: string;
}
// Post now requires id, title, body, createdAt, updatedAt
const post: Post = {
id: 1,
title: "Hello",
body: "World",
createdAt: new Date(),
updatedAt: new Date(),
};Declaration Merging
Interfaces with the same name merge automatically. Only interfaces do this. Types can't.
interface Config {
port: number;
}
interface Config {
host: string;
}
// Config is now { port: number; host: string }
const config: Config = { port: 3000, host: "localhost" };This is how libraries extend built-in types. Express, Fastify, and other frameworks use it to let you augment request objects.
Type Aliases
A type alias can represent anything. Objects, primitives, unions, tuples, functions.
type ID = string | number;
type Pair<T> = [T, T];
type Handler = (req: IncomingMessage, res: ServerResponse) => void; // from "node:http"
type Point = {
x: number;
y: number;
};
const id: ID = "abc-123";
const coords: Pair<number> = [10, 20];
const origin: Point = { x: 0, y: 0 };Interface vs Type: When to Use Which
Use interface for object shapes that might be extended or merged. Use type for everything else: unions, tuples, mapped types, conditional types.
// Interface: object shapes, especially public APIs
interface Repository {
findById(id: string): Promise<User | null>;
save(user: User): Promise<void>;
}
// Type: unions, computed types, anything non-object
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
type StringOrNumber = string | number;
type UserKeys = keyof User;Many teams just pick one and stick with it. Both work for object shapes. The difference only matters at the edges.
Union Types
A union means "one of these types." Use the | operator.
type Status = "pending" | "active" | "disabled";
function setStatus(status: Status): void {
console.log(`Status: ${status}`);
}
setStatus("active"); // OK
// setStatus("unknown"); // Error: '"unknown"' is not assignable
type Input = string | number | null;
function normalize(input: Input): string {
if (input === null) return "none";
if (typeof input === "number") return input.toString();
return input; // narrowed to string
}
console.log(normalize(42)); // "42"
console.log(normalize("hi")); // "hi"
console.log(normalize(null)); // "none"Discriminated Unions
This is the big one. Discriminated unions — add a literal type or kind field to each variant. TypeScript narrows the entire object based on that field.
Go's type switch, but checked at compile time.
interface HttpSuccess {
kind: "success";
status: number;
data: unknown;
}
interface HttpError {
kind: "error";
status: number;
message: string;
}
interface HttpRedirect {
kind: "redirect";
status: number;
location: string;
}
type HttpResponse = HttpSuccess | HttpError | HttpRedirect;
function handleResponse(res: HttpResponse): string {
switch (res.kind) {
case "success":
return `OK: ${JSON.stringify(res.data)}`;
case "error":
return `Error ${res.status}: ${res.message}`;
case "redirect":
return `Redirect to ${res.location}`;
}
}
console.log(handleResponse({ kind: "success", status: 200, data: { id: 1 } }));
// 'OK: {"id":1}'
console.log(handleResponse({ kind: "redirect", status: 301, location: "/new" }));
// "Redirect to /new"Each case narrows res to the specific variant. Full autocomplete and type safety inside each branch.
Exhaustive Switches with never
Someone adds a new variant to the union. You want the compiler to catch every switch that doesn't handle it. Use never.
function assertNever(value: never): never {
throw new Error(`Unhandled value: ${value}`);
}
function describeResponse(res: HttpResponse): string {
switch (res.kind) {
case "success":
return "success";
case "error":
return "error";
case "redirect":
return "redirect";
default:
return assertNever(res);
// If you add a new variant and forget to handle it,
// TypeScript errors: "Argument of type 'X' is not assignable to 'never'"
}
}Put this in every discriminated union switch. It's your safety net.
Intersection Types
Intersections combine types with &. The result has all properties from both.
interface HasId {
id: string;
}
interface HasTimestamps {
createdAt: Date;
updatedAt: Date;
}
type Entity = HasId & HasTimestamps;
const entity: Entity = {
id: "abc",
createdAt: new Date(),
updatedAt: new Date(),
};Like multiple interface extension, but works with type aliases too.
type WithPagination<T> = T & {
page: number;
pageSize: number;
total: number;
};
interface UserList {
users: User[];
}
type PaginatedUsers = WithPagination<UserList>;
// { users: User[]; page: number; pageSize: number; total: number }Index Signatures and Record
When you don't know the exact keys but know the value type, use an index signature.
interface EnvVars {
[key: string]: string | undefined;
}
const env: EnvVars = {
NODE_ENV: "production",
PORT: "3000",
};
const port = env["PORT"]; // string | undefinedRecord is the cleaner way to write the same thing when your keys are a known set.
type LogLevel = "debug" | "info" | "warn" | "error";
const logColors: Record<LogLevel, string> = {
debug: "gray",
info: "blue",
warn: "yellow",
error: "red",
};
// Missing a key? Compiler error.
// Extra key? Compiler error.
console.log(logColors.warn); // "yellow"Record<string, T> is equivalent to an index signature. Record<SomeUnion, T> forces every member of the union to be present.
type Route = "/users" | "/posts" | "/health";
type Method = "GET" | "POST";
const handlers: Record<Route, Record<Method, string>> = {
"/users": { GET: "listUsers", POST: "createUser" },
"/posts": { GET: "listPosts", POST: "createPost" },
"/health": { GET: "healthCheck", POST: "notAllowed" },
};
console.log(handlers["/users"]["GET"]); // "listUsers"TypeScript Enums
TypeScript has enums, and you'll see them in older codebases. They look like Java or C# enums and compile to a real JavaScript object at runtime.
// Enum — compiles to a runtime object
enum Direction { Up = "UP", Down = "DOWN" }
console.log(Direction.Up); // "UP"// String union — no runtime output, just types
type DirectionUnion = "UP" | "DOWN";The compiled JS for the enum is an object lookup table that ships in your bundle. The string union produces zero runtime code. Unions also serialize cleanly to JSON (no transformation needed), work without an import when you just need the string, and tree-shake automatically. The TypeScript community has largely settled on string unions for new code — use enums only when you need reverse mapping (Direction[value]) or are matching an existing Java/C# API contract.
Key Takeaways
- Use
interfacefor object shapes you'll extend or that libraries might merge. Usetypefor unions, tuples, and computed types. - Discriminated unions with a literal
kindortypefield are the TypeScript equivalent of sum types. Use them everywhere. - Always add an exhaustive check with
neverin discriminated union switches. It catches missing cases at compile time. - Intersection types (
&) combine types. Use them to compose reusable pieces. Record<K, V>is your go-to for typed dictionaries. When K is a union, it guarantees every key is present.
🎁 What if you could write a single fetch function that returns a User when you pass /users/:id and a Post when you pass /posts/:id — and the compiler knows the return type from the URL string alone, with no overloads?