How can we utilise the const assertion in TypeScript to flip the script and define types from immutable data?
Since TypeScript 3.4, we’ve been able to use the as const
notation for creating “const assertions” on our literals. This is used to signal to the compiler that any object properties of the literal are readonly, any array literals are readonly, and lastly that any literal types used cannot be widened.
For example:
const foo = {bar: "baz"} as const;
Means that the object foo
has a single property bar
such that its value is of type ”baz”
. This is also an example of a killer feature of TypeScript known as literal types, whereby specific instances of a string or number can be used as a type.
If you look at the documentation for const assertions, they cite several examples of how this feature can be useful, including the ability to:
All the above examples are great ways to utilise the const assertion in your code, but I think I’ve found another really nifty use for them: defining union types from immutable data. This can be used in order to make the usages of such data more type-safe, without the additional maintenance overhead!
Let me explain through a worked example…
#typescript