Patterns & principles · 9 of 10 · 15 min read
DRY, KISS and YAGNI
Three principles read through the type system — what DRY means for types, why a clever type is usually the wrong answer, and the generic nobody needed.
- Principles
- Good practice
These three principles predate TypeScript and most discussions of them stay at the level of functions. The type system gives each one a second, sharper meaning — and in one case it makes the principle much easier to violate.
DRY, for types
The duplication that matters is a shape written more than once:
// Declared twice: the second one will fall behind.
interface User { id: number; name: string; email: string }
interface UserResponse { id: number; name: string; email: string; token: string }
// Declared once, extended:
interface User2 { id: number; name: string; email: string }
interface UserResponse2 extends User2 { token: string }
const response: UserResponse2 = { id: 1, name: "Ana", email: "a@b.c", token: "x" };
console.log(response.token);
Rename email to emailAddress in the first pair and the compiler reports nothing — the two
interfaces were never connected, so the program now has two different Users and one of them is
wrong. The second pair is one declaration with one extension, and the rename propagates.
The toolkit for not repeating a shape is small and worth knowing by reflex:
| Duplication | Fix |
|---|---|
| A subset of a shape | Pick<T, K> |
| A shape minus a field | Omit<T, K> |
| A patch payload | Partial<T>, or Pick<T,"id"> & Partial<Omit<T,"id">> |
| The shape of an existing value | typeof value |
| What a function returns | ReturnType<typeof fn> |
| What an async function returns | Awaited<ReturnType<typeof fn>> |
| One property’s type | T["property"] |
| An array’s element type | T[number] |
| The options of a union | as const + typeof x[number] |
| A validator and a type | derive the type from the validator |
interface User { id: number; name: string; email: string; passwordHash: string }
type PublicUser = Pick<User, "id" | "name">;
type NewUser = Omit<User, "id" | "passwordHash">;
type UserPatch = Pick<User, "id"> & Partial<Omit<User, "id">>;
const draft: NewUser = { name: "Ana", email: "a@b.c" };
console.log(draft.name);
Four related types, one source. The rename now reaches all of them.
Where DRY stops
Two shapes that happen to match today are not duplication:
// These are the same shape and should stay separate declarations.
interface CreateUserRequest { name: string; email: string }
interface UpdateProfileForm { name: string; email: string }
Deriving one from the other couples an API contract to a form, and the next change to either one breaks the wrong thing. The test is not “do these look the same” but “must these change together”.
The same applies to a validation schema and a database row, to a DTO and a domain model, and to two components that render similar markup. Coincidental duplication is cheaper than the wrong abstraction, and the type system makes the wrong abstraction particularly expensive: an over-shared type propagates its next change to every consumer.
KISS, for types
A type’s job is to be read. These two say the same thing:
// Clever:
type Clever<T> = T extends Record<string, unknown>
? { [K in keyof T as T[K] extends Function ? never : K]: T[K] extends object ? Clever<T[K]> : T[K] }
: T;
// Simple:
interface UserData {
id: number;
name: string;
address: { city: string; country: string };
}
const data: UserData = { id: 1, name: "Ana", address: { city: "Bogotá", country: "CO" } };
console.log(data.address.city);
The first is impressive and the second is maintainable. The questions worth asking before shipping a complicated type:
- How many call sites does it serve? One or two means write the type out. Hundreds across a library boundary is where the machinery pays.
- What does the error message look like when it fails? A deep conditional produces errors that name intermediate types nobody recognises.
- Can the next person extend it? If the answer is no, the next feature will route around it
with an
as, and the type will be wrong as well as complicated.
The clearest symptom of a type that is too clever is @ts-expect-error appearing near it.
any versus unknown
The simple-versus-safe decision that comes up most often:
function handleUnknown(value: unknown) {
// Nothing is allowed until it is narrowed — which is the point.
if (typeof value === "string") return value.toUpperCase();
if (typeof value === "number") return value.toFixed(2);
return String(value);
}
function handleAny(value: any) {
return value.toUpperCase(); // compiles, throws on a number
}
console.log(handleUnknown(42), typeof handleAny);
unknown is the honest “I do not know yet”: assignable from anything, usable only after a check.
any turns checking off, and it spreads — every expression derived from an any is also any,
so one annotation can silently disable type checking across a whole call chain.
any is defensible in three places, all of them narrow: a quick, marked step during a migration;
the parameter of a type guard that accepts genuinely anything; and the inside of a utility whose
public signature is correct even though the body cannot be expressed. Everywhere else unknown
plus a narrowing function is both simpler to reason about and shorter to write than the bug any
eventually produces.
A related small one: object as a parameter type is almost never what is meant.
function countKeys(value: object) {
// return value.length; // no properties are known
return Object.keys(value).length;
}
function countKeysBetter(value: Record<string, unknown>) {
return Object.keys(value).length;
}
console.log(countKeys({ a: 1 }), countKeysBetter({ a: 1 }));
object only says “not a primitive” — it has no members, so nothing can be read from it, and it
still accepts arrays and functions. Record<string, unknown> says what was actually meant.
YAGNI, for types
The type-system version of speculative generality is a type parameter nobody passes:
// Written for a future that never arrived:
interface Repository<T, TId, TQuery, TResult> {
find(id: TId): Promise<TResult | null>;
search(query: TQuery): Promise<TResult[]>;
}
// What was needed:
interface UserRepository {
find(id: number): Promise<User | null>;
search(name: string): Promise<User[]>;
}
interface User { id: number; name: string }
declare const repo: UserRepository;
console.log(typeof repo.find);
Four type parameters, one implementation, and every call site now reads
Repository<User, number, string, User>. The generic version is not more flexible in any way that
was ever used — it is the same interface with the information moved to where callers have to repeat
it.
Things built “for later” that usually are not needed:
- A generic parameter with exactly one instantiation. Make it concrete; generalise when the second case arrives, which is a mechanical refactor.
- An abstract base class with one subclass. The subclass is the class.
- A
BaseEntityevery model extends for two fields. Two fields are cheaper than a hierarchy. - An options object with flags nothing sets. Each one is a branch to maintain and test.
- A plugin interface before there is a second plugin.
The cost is not the code; it is that every reader has to understand a generality that never pays off, and every change has to preserve it.
The one place to be speculative
Validate at the boundary, even before anything has gone wrong there:
interface ApiUser { id: number; name: string }
// Not this — `json()` returns `any`, so nothing below is checked.
async function loadLoose(url: string): Promise<ApiUser> {
const response = await fetch(url);
return response.json() as ApiUser;
}
// This — one check, and everything downstream is genuinely typed.
function isApiUser(value: unknown): value is ApiUser {
return (
typeof value === "object" && value !== null &&
typeof (value as ApiUser).id === "number" &&
typeof (value as ApiUser).name === "string"
);
}
async function load(url: string): Promise<ApiUser> {
const data: unknown = await (await fetch(url)).json();
if (!isApiUser(data)) throw new Error("unexpected response shape");
return data;
}
console.log(typeof loadLoose, typeof load);
An annotation on data that came from outside the program is a hope, not a check. One validator at the edge is the single highest-value piece of “defensive” work in a TypeScript codebase — and unlike the YAGNI examples above, it is needed on day one.
Common mistakes
Re-declaring a shape instead of deriving it
Mistake. interface UserDto { id: number; name: string } alongside interface User.
Why it fails. Two declarations of one concept; the next rename updates one.
What to do instead. Pick<User, "id" | "name">, or typeof / ReturnType when the source is
a value.
Sharing a type because two shapes match
Mistake. Making a form type and an API request type the same interface. Why it fails. They are independent concepts that happen to agree. Coupling them means the next API change edits the form. What to do instead. Two declarations, and a mapping function where they meet — which is also where the drift gets caught.
as instead of a check at a boundary
Mistake. return response.json() as User.
Why it fails. json() is any, the assertion is unverified, and a changed API produces
undefined property access deep inside the application rather than an error at the edge.
What to do instead. Parse into unknown, validate once with a predicate or a schema library,
and let everything downstream rely on the type.
Check yourself
4 questions from the bank on what you just read. Answering here does not affect your quiz history.
What does DRY mean for *types* specifically?
Where you put the type boundary decides how far a bad value can travel.
What is wrong with trusting this response shape?
async function loadUser(id: number): Promise<User> {
const response = await fetch(`/users/${id}`);
return response.json();
}When is any the right choice over unknown?
What is the problem with typing a function parameter as object?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.