Problem: You need to represent an empty number


Problem: You need to represent an empty number.

Hack: Use 0, -1, or "".

The real solution: Use null. That's what it's for. Null says, "This has no value".

0, -1, and "" are a lie.

Oh, and "lying" is a problem because it hurts type safety too.

If I use 0 to represent a missing value, TypeScript won't protect me - it can't "see" that 0 is a special case I need to handle.

But if the value can be null, TypeScript forces me to handle it. That's a win.
TypeScript can't ensure I handle 0, or -1 as a special case, since they're just other numbers.

So, I would type this as:

type User = {
userId: number | null;
}

This way, TypeScript ensures I handle the null. 👍

View original on X