The TypeScript practices that help you turn business rules into types—and make invalid states harder to represent.
TypeScript is easy to learn.
You learn interfaces.
Then type aliases.
Then unions, generics, utility types, and maybe a few mapped types.
Eventually, you can look at a JavaScript object and confidently add a type to it.
But there’s a point where TypeScript stops being about adding types.
It becomes about designing types.
And that’s a very different skill.
Originally published on Medium.
Consider this:
type Payment = {
status: 'SUCCESS' | 'FAILED'
transactionId?: string
error?: string
}
It looks perfectly reasonable.
But what states does this type actually allow?
All of these:
{
status: 'SUCCESS'
}
{
status: 'SUCCESS',
error: 'Something went wrong'
}
{
status: 'FAILED',
transactionId: '123'
}
{
status: 'FAILED',
error: 'Something went wrong'
}
The type doesn’t know which combinations make sense.
The problem isn’t that TypeScript isn’t powerful enough.
We’ve modeled the domain poorly.
A better model is:
type Payment =
| {
status: 'SUCCESS'
transactionId: string
}
| {
status: 'FAILED'
error: string
}
Now the type system understands the business rule.
A successful payment has a transaction ID.
A failed payment has an error.
Invalid combinations become difficult—or impossible—to represent.
This is where TypeScript becomes much more interesting.
The goal isn’t to put types everywhere.
The goal is to make your types communicate the rules of your application.
Here are some practices that help you do exactly that.
1. Stop Using any When You Actually Mean “I Don’t Know”
One of the easiest ways to make a TypeScript error disappear is:
const response: any = await fetchData()
And sometimes that’s exactly what happens.
You have an error.
You’re in the middle of implementing something.
You don’t immediately understand the type.
So you write any.
The compiler stops complaining.
But you’ve also stopped TypeScript from helping you.
Once any enters your code:
const response: any = await fetchData()
response.user.profile.name // not checked
response.foo.bar.baz // not checked
TypeScript won’t protect you from any of it.
Use unknown when the value is genuinely unknown
const response: unknown = await fetchData()
Now TypeScript forces you to establish what the value actually is.
if (typeof response === 'string') {
console.log(response.toUpperCase())
}
Or for more complex data, validate it at the boundary.
This distinction is important:
unknownmeans “I don’t know yet.”anymeans “I don’t want TypeScript involved.”
Those are very different statements.
If you’re dealing with external data, unknown is usually the more honest starting point.
2. Don’t Type What TypeScript Already Knows
Strongly typed code doesn’t mean explicitly annotating every variable.
This:
const name: string = 'Akshat'
const age: number = 30
const active: boolean = true
isn’t necessarily better than:
const name = 'Akshat'
const age = 30
const active = true
TypeScript already knows the types.
Adding annotations everywhere creates noise without adding information.
Explicit types become valuable when they communicate something meaningful.
For example:
function calculateTotal(
items: Product[],
discount: number,
): number {
// ...
}
Here the function signature is part of the API contract.
That’s useful.
A good question to ask is:
Does this annotation communicate something TypeScript couldn’t infer?
If the answer is no, you probably don’t need it.
3. Use as const When Values Are Also Types
Consider:
const STATUS = {
ACTIVE: 'ACTIVE',
INACTIVE: 'INACTIVE',
}
Sometimes you want those values to remain literal types.
That’s where as const becomes useful:
const STATUS = {
ACTIVE: 'ACTIVE',
INACTIVE: 'INACTIVE',
} as const
Now:
type Status = typeof STATUS[keyof typeof STATUS]
produces:
'ACTIVE' | 'INACTIVE'
This pattern is especially useful when you need the values at runtime and the type at compile time.
For example:
export const ALTERNATE_CODE_TYPES = {
CHARGE_CODE: 'CHARGE_CODE',
NFTP_MDG_CODE: 'NFTP_MDG_CODE',
FACT_MDG_CODE: 'FACT_MDG_CODE',
CW1_CHARGE_CODE: 'CW1_CHARGE_CODE',
} as const
export type AlternateCodeType =
typeof ALTERNATE_CODE_TYPES[keyof typeof ALTERNATE_CODE_TYPES]
Now the object and type come from the same source.
You don’t have to maintain:
type AlternateCodeType =
| 'CHARGE_CODE'
| 'NFTP_MDG_CODE'
| 'FACT_MDG_CODE'
| 'CW1_CHARGE_CODE'
separately.
One source of truth is easier to maintain.
4. Use Union Types When the Domain Has a Fixed Set of States
If something can only be one of a few values, make that explicit.
Instead of:
function setStatus(status: string) {
// ...
}
use:
type Status = 'pending' | 'approved' | 'rejected'
function setStatus(status: Status) {
// ...
}
Now this is valid:
setStatus('approved')
while this isn’t:
setStatus('something-else')
The narrower your type, the more useful the compiler becomes.
This isn’t just about autocomplete.
It improves:
- refactoring
- documentation
- error detection
- API design
- discoverability
If your business domain permits three values, don’t model it as an arbitrary string.
5. Don’t Reach for Enums Automatically
Enums have their place.
But not every set of constants needs to be an enum.
If you only need a compile-time union:
type Status = 'ACTIVE' | 'INACTIVE'
may be enough.
If you need runtime values too:
const STATUS = {
ACTIVE: 'ACTIVE',
INACTIVE: 'INACTIVE',
} as const
type Status = typeof STATUS[keyof typeof STATUS]
You now have both.
The important thing to understand is that a TypeScript type disappears at runtime.
An object does not.
So ask yourself:
Do I need runtime behaviour, or do I only need compile-time constraints?
Choose accordingly.
6. Make Invalid States Impossible to Represent
This is perhaps the most important principle in this entire article.
Suppose you are building a form.
It can be:
- loading
- ready
- submitting
- successful
- failed
A common model is:
type FormState = {
loading: boolean
submitting: boolean
error?: string
data?: FormData
}
Now you can accidentally represent:
{
loading: true,
submitting: true,
data: {...},
error: 'Something went wrong'
}
What does that state mean?
Your type doesn’t know.
A better design:
type FormState =
| { status: 'loading' }
| { status: 'ready'; data: FormData }
| { status: 'submitting'; data: FormData }
| { status: 'success'; data: FormData }
| { status: 'error'; error: string }
Now each state describes exactly what is available.
function render(state: FormState) {
switch (state.status) {
case 'loading':
return 'Loading...'
case 'ready':
return state.data
case 'submitting':
return 'Submitting...'
case 'success':
return state.data
case 'error':
return state.error
}
}
This is the power of discriminated unions.
Instead of representing your application as a collection of independent booleans and optional properties, you represent it as a set of valid states.
That is a much stronger model.
7. Be Careful With Optional Properties
Optional properties are useful.
But they are also an easy way to hide uncertainty.
Consider:
type User = {
id?: string
name?: string
email?: string
}
Now every consumer has to account for the possibility that everything is missing.
But perhaps the actual domain says:
A User always has an ID, name, and email.
Then write:
type User = {
id: string
name: string
email: string
}
Optional properties should represent actual optionality.
They shouldn’t be a substitute for saying:
“I’m not sure what this API returns.”
If the uncertainty comes from an external system, deal with it at the boundary.
Don’t make your entire application uncertain because one external system is.
8. Understand null vs undefined
This distinction becomes surprisingly important in real applications.
Consider:
type User = {
middleName: string | null
}
This could mean:
The property exists, but there is intentionally no middle name.
Compare that with:
type User = {
middleName?: string
}
which often means:
The property itself may not exist.
This distinction matters especially for APIs.
Imagine a PATCH request:
{
middleName: null
}
might mean:
Clear the middle name.
While:
{}
might mean:
Don’t change the middle name.
If your type doesn’t capture that distinction, subtle bugs can appear at the API boundary.
Types aren’t just compiler annotations.
They should communicate the semantics of your data.
9. Use satisfies Instead of Blindly Asserting Types
Consider:
type Config = {
timeout: number
retries: number
}
You could write:
const config = {
timeout: 5000,
retries: 3,
} as Config
But as is an assertion.
You’re telling TypeScript:
“Trust me.”
A better option in many cases is:
const config = {
timeout: 5000,
retries: 3,
} satisfies Config
Now TypeScript verifies that the object conforms to Config while preserving the specific inferred type of the object.
A useful mental model:
as— Treat this as this type.satisfies— Verify that this value satisfies this type.
That distinction makes satisfies particularly useful for configuration objects, mappings, and lookup tables.
10. Treat as as a Boundary, Not a Default Tool
Type assertions are sometimes necessary.
But this:
const user = response as User
doesn’t validate anything.
If your API actually returned:
{
username: 'akshat'
}
TypeScript isn’t going to complain about your assertion.
You’ve simply told the compiler to trust you.
This is especially dangerous around:
- API responses
- localStorage
- URL parameters
- environment variables
- user input
- third-party libraries
When data enters your application from outside TypeScript’s control, consider validating it.
For example, a runtime schema can establish:
“This data actually matches the shape my application expects.”
That’s a much stronger guarantee than:
value as User
TypeScript is excellent at compile-time guarantees.
It isn’t a runtime validation system.
The Real Goal: Model the Domain
Once you start thinking this way, TypeScript becomes less about syntax.
You stop asking:
“How do I type this object?”
And start asking:
“What states can this object actually be in?”
You stop asking:
“Should I make this property optional?”
And start asking:
“Is this property genuinely optional, or am I hiding uncertainty?”
You stop asking:
“Can I use as here?”
And start asking:
“Can I prove this value has the type I claim it has?”
That’s the shift.
Good TypeScript isn’t about adding more types.
It’s about making the types meaningful.
A Simple Rule to Remember
When designing a type, ask yourself three questions:
1. What states are actually valid?
If you can represent invalid states, your model probably needs improvement.
2. What does the compiler already know?
Don’t add annotations just for the sake of adding annotations.
3. Where does this data become trustworthy?
The farther you get from an external boundary, the more confident your types should become.
The best TypeScript code is not the code with the most complicated types.
It’s the code where the types make the correct implementation feel natural—and the incorrect implementation difficult to write.
And once you start designing types this way, TypeScript stops feeling like a layer on top of JavaScript.
It starts becoming part of your application’s architecture.
This is Part 1 of a two-part series on writing better TypeScript. In Part 2, we look at practical patterns for using TypeScript to make large codebases more maintainable.



