Member-only story
What Is the Empty Object {} Type in TypeScript?
Here’s why you need to use a special type of Record
instead of {}
to represent empty objects in TypeScript.
TypeScript’s type system is great, until you realize you have to memorize a bunch of meaningless trivia.
Case in point, {}
doesn’t actually mean “an empty object” in TypeScript!
Instead, it represents “any non-nullish value.” Nullish means “null or undefined” — the same as used in ??
, the “nullish coalescing operator.”
Here’s what happens when you try to use the {}
type in TypeScript.
type EmptyObjWrong = {}
let objWrong: EmptyObjWrong = { name: "Derek" }
objWrong = "Intentionally allowed by TypeScript."
// No error from the TypeScript compiler in either case! 🤯
The compiler happily accepts this because {}
only guarantees the object has at least no properties—not exactly no properties.
This is the type of bug that you’re quite unlikely to catch when writing or reviewing TypeScript code, but thankfully there’s an ESLint rule for it.
Let’s talk about that rule for a second before I show you the correct solution for TypeScript empty object types using Record
.