Practical patterns for writing TypeScript that remains readable, maintainable, and useful as your application grows.
This is Part 2 of a two-part series on writing better TypeScript.
In Part 1, we looked at how to model domains and make invalid states harder to represent. This article focuses on the practical patterns that keep TypeScript code maintainable as the codebase grows.
Originally published on Medium.
Knowing TypeScript syntax is one thing.
Using TypeScript well in a large codebase is another.
Once an application grows beyond a few thousand lines, the biggest TypeScript problems usually aren’t caused by not knowing what a generic is.
They’re caused by things like:
- abstractions that are too clever
- types that are too broad
- assertions everywhere
- duplicated contracts
- unreadable generics
- functions with ambiguous APIs
- types scattered across the project
- compiler settings that aren’t taken seriously
In a small project, these problems might be harmless.
In a large application with dozens of developers, they compound.
A type that is slightly confusing today becomes technical debt six months later.
So this article isn’t about obscure TypeScript tricks.
It’s about practical decisions that make TypeScript code easier to understand and maintain.
1. Use Generics to Express Relationships
Generics are often introduced as a way to make functions reusable.
That’s true.
But their more important purpose is expressing relationships between types.
Consider:
function getFirst<T>(items: T[]): T | undefined {
return items[0]
}
If you pass:
const users: User[] = [...]
TypeScript knows:
const user = getFirst(users)
// User | undefined
And if you pass:
const products: Product[] = [...]
you get:
const product = getFirst(products)
// Product | undefined
The generic preserves the relationship between input and output.
Compare that with:
function getFirst(items: unknown[]): unknown {
return items[0]
}
Now you’ve lost that relationship.
A useful question when writing a generic is:
What relationship between these types am I trying to preserve?
If you can’t answer that, you might not need a generic.
2. Don’t Turn Everything Into a Generic
Generics are powerful.
That’s exactly why they are easy to overuse.
You can write something like:
function processData<
T extends Record<string, unknown>,
K extends keyof T,
R extends ...,
>(...) {
// ...
}
And feel pretty good about yourself.
Then someone else opens the file six months later.
They feel something else.
Complex generics introduce cognitive overhead.
If a simple function communicates the intent:
function processUser(user: User) {
// ...
}
then use the simple function.
The goal isn’t to demonstrate how much TypeScript you know.
The goal is to make the code easier to understand.
Use generics when they express a meaningful relationship—not simply because they can.
3. Prefer Type Narrowing Over Casting
This is tempting:
const value = something as string
But you’re bypassing the compiler’s uncertainty.
Instead, narrow the value:
if (typeof something === 'string') {
console.log(something.toUpperCase())
}
For objects, create a type guard when appropriate:
function isUser(value: unknown): value is User {
return (
typeof value === 'object'
&& value !== null
&& 'id' in value
&& 'name' in value
)
}
Then:
if (isUser(value)) {
console.log(value.name)
}
The distinction is important:
Casting says:
“Trust me.”
Narrowing says:
“Here’s why this value is safe to treat this way.”
The second approach gives the type system something to work with.
4. Use never to Catch Incomplete Logic
Imagine:
type Status =
| 'pending'
| 'approved'
| 'rejected'
You might write:
function getLabel(status: Status) {
switch (status) {
case 'pending':
return 'Pending'
case 'approved':
return 'Approved'
case 'rejected':
return 'Rejected'
}
}
That’s fine.
But what happens six months later when someone adds:
type Status =
| 'pending'
| 'approved'
| 'rejected'
| 'cancelled'
There might be dozens of places that depend on Status.
You want the compiler to tell you where your assumptions are incomplete.
That’s where never can help:
function assertNever(value: never): never {
throw new Error(`Unhandled value: ${value}`)
}
function getLabel(status: Status) {
switch (status) {
case 'pending':
return 'Pending'
case 'approved':
return 'Approved'
case 'rejected':
return 'Rejected'
default:
return assertNever(status)
}
}
Now adding a new status produces a compiler error.
This is especially valuable in large codebases.
The type definition becomes the source of truth, and the compiler identifies all the places that need to change.
5. Use readonly to Communicate Intent
Types aren’t only about what values are allowed.
They’re also about how those values are supposed to be used.
Consider:
type User = {
readonly id: string
name: string
}
Now:
user.id = '123'
is rejected.
You can also make collections readonly:
function processUsers(users: readonly User[]) {
// ...
}
Now the function can read the collection without implying that it owns or mutates it.
This is particularly useful for:
- configuration
- shared data
- constants
- function parameters
- immutable state
The benefit isn’t just preventing a mutation.
It’s communicating intent to every developer who reads the type.
6. Don’t Use Record<string, unknown> as a Replacement for Real Types
You’ve probably seen code like:
function process(data: Record<string, unknown>) {
// ...
}
Sometimes that’s exactly what you need.
If the function accepts arbitrary key-value data, great.
But if you actually know what the object represents, model it.
Instead of:
function process(data: Record<string, unknown>) {
// ...
}
use:
type User = {
id: string
name: string
}
function process(user: User) {
// ...
}
The difference might look small.
The impact isn’t.
The second version gives you:
- autocomplete
- documentation
- refactoring support
- compile-time guarantees
- clearer intent
Broad types are useful at genuinely dynamic boundaries.
They shouldn’t become the default representation for everything.
7. Make Function APIs Self-Documenting
Consider:
createUser(
'Akshat',
'akshat@example.com',
true,
false,
)
What does each boolean mean?
You have to remember the function signature.
Now compare:
createUser({
name: 'Akshat',
email: 'akshat@example.com',
sendWelcomeEmail: true,
isAdmin: false,
})
The API explains itself.
type CreateUserOptions = {
name: string
email: string
sendWelcomeEmail: boolean
isAdmin: boolean
}
function createUser(options: CreateUserOptions) {
// ...
}
This becomes increasingly valuable as functions grow.
A function with two arguments might be perfectly readable.
A function with seven arguments is usually asking for trouble.
TypeScript gives us a convenient way to make complex function APIs much more explicit.
Use it.
8. Organize Types Around the Domain
A common pattern in large applications is a global types.ts file.
It starts small.
Then another developer adds a type.
Then another.
A year later:
types.ts contains hundreds of unrelated types.
Finding the type you need becomes a project-wide search exercise.
Instead, keep types close to the domain they describe.
For example:
users/
user.types.ts
user.service.ts
user.repository.ts
payments/
payment.types.ts
payment.service.ts
payment.repository.ts
facilities/
facility.types.ts
facility.service.ts
facility.repository.ts
The exact architecture isn’t important.
The principle is.
Types belong to the domain they describe.
When you understand where the business logic lives, you should have a good idea where its types live too.
9. Don’t Let the Type System Become More Complicated Than the Business Logic
TypeScript can do some incredible things.
Mapped types.
Conditional types.
Template literal types.
Recursive types.
infer.
Distributive conditional types.
You can build almost anything.
That doesn’t mean you should.
Consider a type like:
type Magic<T> =
T extends infer U
? U extends Record<string, unknown>
? {
[K in keyof U as K extends `${string}Id`
? K
: never]: U[K]
}
: never
: never
There are legitimate use cases for sophisticated type-level programming.
But there is also a point where you’ve created more complexity than you’ve removed.
If the next developer needs to understand a complicated type before they can understand the business logic, stop and ask:
Could this be simpler?
Sometimes the answer is no.
Sometimes the complexity is justified.
But don’t confuse cleverness with quality.
The best TypeScript is often boring.
Readable types beat impressive types.
10. Take tsconfig Seriously
One of the easiest ways to undermine TypeScript is to configure it so that it doesn’t catch the problems you’re relying on it to catch.
At minimum, understand options such as:
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true
}
}
The exact configuration will depend on your project.
A legacy codebase may not be able to enable every strict option immediately.
That’s fine.
What’s important is understanding what your compiler is checking.
Especially:
"strict": true
Strict mode isn’t about making TypeScript annoying.
It’s about asking the compiler to be more honest about uncertainty.
And the whole reason we use TypeScript is to catch problems before users do.
The Bigger Picture
None of these practices are particularly useful because they’re clever TypeScript tricks.
They’re useful because they make your codebase easier to reason about.
Consider what happens when a new developer joins your team.
They encounter:
type Payment =
| {
status: 'SUCCESS'
transactionId: string
}
| {
status: 'FAILED'
error: string
}
They immediately know something about the domain.
A successful payment has a transaction ID.
A failed payment has an error.
The type itself communicates the business rule.
That’s what good TypeScript should do.
It shouldn’t just tell you:
“This property is a string.”
It should tell you:
“This is how this part of the system is supposed to behave.”
A Practical TypeScript Checklist
Before committing a piece of TypeScript, I like to ask:
- Is there an
anyhere that could beunknownor a real type? - Am I writing a type annotation that TypeScript can already infer?
- Are my types representing valid domain states?
- Am I making something optional because it’s genuinely optional?
- Could a union represent this state more accurately?
- Am I using
asbecause the value is actually safe, or because I want the error to disappear? - Does this generic express a meaningful relationship?
- Is this abstraction easier to understand than the code it replaced?
- Does the function API communicate what its arguments mean?
- Would
readonlymake the intended ownership or immutability clearer? - Will the compiler tell me when this domain changes?
- Can another developer understand this type without having to decode it?
That last question is perhaps the most important.
TypeScript Is a Design Tool
The more TypeScript you write, the less interesting the syntax becomes.
The interesting part is what you choose to express.
You can use TypeScript to describe:
“This is an object with some strings.”
Or you can use it to describe:
“This operation can be in one of four states, and each state guarantees a different set of properties.”
The second is much more valuable.
That’s why good TypeScript isn’t measured by how many advanced features a developer knows.
It’s measured by how effectively the type system helps the team understand, change, and maintain the software.
Types should make the codebase easier to reason about—not harder.
And when the compiler can enforce the rules your application already cares about, you’ve moved beyond using TypeScript as a safety net.
You’re using it as part of the architecture.
Thanks for reading.
If you found this article useful, consider sharing it with other developers.
Happy coding!



