Member-only story
6 TypeScript Code Patterns To Make Your Code More Robust
Simple and practical solutions you can apply in daily work

I found out that I repeatedly use some TypeScript code patterns in daily work. Those code patterns aren’t heavy or complex, and they also don’t require a lot of boilerplate code. They’re just simple and practical solutions to resolve a few common problems.
In the next few sections, I’ll share my six favorite TypeScript code patterns.
Jump ahead:
- Use Pick To Implement Interface Segregation Principle
- Const Assertion To Derive Types From Literal Expressions
- Exhaustive Checks With “never” Type
- Use Opaque Type To Simulate Nominal Typing Behavior
- Lookup property type from an Object Type
- Refactor Excessive Function Parameters With Destructing Assignments
Use Pick To Implement Interface Segregation Principle
The interface segregation principle is defined as:
Clients should not be forced to implement interfaces they do not use.
Let’s say we have a Client
type, it’s used in multiple places. Sometimes, only a subset of properties is used. According to the interface segregation principle, the function parameter with the type should be the minimal type required.
We can use Pick
utility type to exclude unused properties from the Client
type. As shown in the code snippet below, only the name
and active
properties are picked. Thus the ClientSummary
type represents a smaller, more specific interface that only includes the properties it needs.
An alternative way is to use Exclude
utility type as below:
type ClientSummary = Exclude<Client, 'dateOfBirth'>;
However, Pick
is more robust because no changes are required when additional properties are added…