TypeScript tip: Try to avoid optional fields


TypeScript tip: Try to avoid optional fields.

They cause two problems:
1. They reduce type safety.
2. There's no type-safe way to enforce when the field should be populated.

Solution: Often optional fields can be eliminated by declaring separate and more specific types.

Principle: The more information we can provide TypeScript, the more it can help us.
The problem is, an optional field doesn't specify when it must be populated.

This creates two risks:

1. An optional field may not be populated when it logically should be.

2. An optional field may be populated when it logically shouldn't be.
An exception: Optional props on React components are fine - as long as they specify a default.

It in TypeScript, optional fields don’t support a default, so I avoid them otherwise.
Here's a wonderful related post by @ploeh that explores this idea further.

The idea is simple - Make impossible states impossible via careful type design.

https://blog.ploeh.dk/2016/02/10/types-properties-software-designing-with-types/

View original on X