Prevent Type Widening of Object Literals with TypeScript's const Assertions

Marius Schulz
InstructorMarius Schulz

Share this video with your friends

Send Tweet

A const assertion is a special type assertion that uses the const keyword instead of a specific type name. When using a const assertion on an object literal expression, all properties will become readonly properties and no literal types within the expression will be widened.

Additional Reading

Andrew Ross
Andrew Ross
~ 2 months ago

ah, so the Object.freeze() method is a wrapper equivalent to the following?

const ORIGIN: Readonly<{ readonly x: 0; readonly y: 0; }> = { x: 0, y: 0 };

Marius Schulz
Marius Schulzinstructor
~ 2 months ago

@Andrew: Not quite. TypeScript's readonly modifier does not have any runtime manifestation — it's completely compiled away, so ORIGIN will have two mutable properties x and y.

Object.freeze(), on the other hand, freezes an object at runtime. When an object is frozen, it can no longer be changes. Fro example, property values can't be changed, and properties can't be removed, added, or reconfigured.

So readonly gives you some protection through type-checking at compile-time, whereas Object.freeze() actually prevents modifications at runtime.