Sub topic 3
Declaration Merging and Choosing TypeScript Shapes
Assume basic type annotations and JavaScript objects, functions, and classes. You should also be able to run the TypeScript compiler or read editor type errors.
Declaration merging and when it helps
TypeScript merges interface declarations that have the same name. The resulting interface contains every member. This is useful when a library lets you add fields to an existing public type.
interface Config {
host: string;
}
interface Config {
port: number;
}
const config: Config = { host: "localhost", port: 8080 };A type alias cannot merge. Repeating the same alias name is an error. Use merging deliberately because a second declaration can change a type far from where it was first defined.
Classes that implement interfaces
A class can implement an interface. The compiler then checks that the class has all required members.
interface Logger {
log(message: string): void;
}
class ConsoleLogger implements Logger {
log(message: string): void {
console.log(message);
}
}implements checks the class's public shape. It does not automatically create properties or change runtime behavior.
Generic interfaces and type aliases
Generics let one shape work with several types.
interface Box<T> {
value: T;
}
type Pair<A, B> = [A, B];
const count: Box<number> = { value: 42 };
const entry: Pair<string, number> = ["age", 30];Deriving and mapping types
Utility types derive shapes from existing types:
interface Todo {
title: string;
done: boolean;
note: string;
}
type Draft = Partial<Todo>;
type Preview = Pick<Todo, "title" | "done">;
type WithoutNote = Omit<Todo, "note">;
type FrozenTodo = Readonly<Todo>;Partial makes properties optional. Pick keeps named properties. Omit removes them. Readonly prevents assignment through that type.
A mapped type applies a rule to every property selected by keyof:
type Flags<T> = { [K in keyof T]: boolean };
type TodoFlags = Flags<Todo>;TodoFlags has title, done, and note, all with type boolean.
Choosing between interface and type alias
Both can describe object shapes and support generics. Prefer an interface for an extendable public object contract or when declaration merging is useful. Prefer a type alias for unions, literal types, tuples, mapped types, or combinations using &. Teams should choose a consistent default, then make exceptions for these capabilities.
Exercise
Which construct should name a result that is either successful or failed?
Show answer
Use a type alias for a discriminated union, such as { ok: true; value: string } | { ok: false; error: Error }.