Joan Llenas put this article together about safer types with TypeScript. There are only two hard things in Computer Science: null and undefined.
Every time we annotate a variable with a Type, that variable can hold either a value of the annotated Type, null, or undefined (and sometimes even NaN!).
That means, to avoid errors like Cannot read property ‘XYZ’ of undefined, we must remember to consistently apply defensive programming techniques every time we use it.
Another tricky aspect of the above fact is that semantically, it’s very confusing what null and undefined should be used for. They can mean different things for different people. APIs also use them inconsistently.
The article then focuses on:
- What can go wrong?
- Maybe to the rescue
- Either to the rescue
And here is an example:
import { Maybe } from "ts.data.maybe";
interface User {
id: number;
nickname: string;
email: string;
bio: Maybe<string>;
dob: Maybe<Date>;
}
We’ve learned that container Types are wrappers for values that provide APIs so we can safely operate with them. Nice one!
[Read More]