DEV Community

Maxim Logunov
Maxim Logunov

Posted on

Understanding Const Assertions in TypeScript

TypeScript, a statically typed superset of JavaScript, has become an indispensable tool for developers aiming to build robust and maintainable applications. One of the powerful features TypeScript offers is const assertions, introduced in TypeScript 3.4. This feature allows developers to create more precise and immutable types, enhancing type safety and reducing the likelihood of runtime errors. In this article, we’ll explore what const assertions are, how they work, and why they are useful.

What Are Const Assertions?

Const assertions are a way to tell TypeScript that a value should be treated as a constant, meaning it cannot be modified after its initial assignment. When you use a const assertion, TypeScript infers the most specific type possible for the value, ensuring that it remains immutable and narrows down the type to its literal value.

The syntax for a const assertion is simple: you append as const to a value or expression. This signals to TypeScript that the value should be treated as a literal type rather than a broader type.

const user = {
  name: "Alice",
  age: 30,
} as const;
Enter fullscreen mode Exit fullscreen mode

In this example, user is treated as an immutable object with specific literal types for its properties. TypeScript will infer the type of user as:

{
  readonly name: "Alice";
  readonly age: 30;
}
Enter fullscreen mode Exit fullscreen mode

Notice that both name and age are marked as readonly, and their types are narrowed down to the exact literal values "Alice" and 30, respectively.

How Const Assertions Work

Const assertions work by enforcing three key behaviors:

  1. Literal Types: The values are inferred as literal types instead of broader types like string or number. For example, "Alice" is inferred as the type "Alice" rather than string.

  2. Readonly Properties: Object properties and array elements are marked as readonly, making them immutable.

  3. Deep Immutability: The immutability is applied recursively to all nested properties and elements.

Let’s look at a few examples to understand this better.

Example 1: Primitive Values

const greeting = "Hello, World!" as const;
Enter fullscreen mode Exit fullscreen mode

Here, greeting is inferred as the literal type "Hello, World!" instead of string. This ensures that greeting cannot be reassigned to another value.

Example 2: Arrays

const numbers = [1, 2, 3] as const;
Enter fullscreen mode Exit fullscreen mode

With the const assertion, numbers is inferred as a readonly tuple:

readonly [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

This means you cannot modify the array or its elements.

Example 3: Objects

const config = {
  apiUrl: "https://api.example.com",
  timeout: 5000,
} as const;
Enter fullscreen mode Exit fullscreen mode

The config object is inferred as:

{
  readonly apiUrl: "https://api.example.com";
  readonly timeout: 5000;
}
Enter fullscreen mode Exit fullscreen mode

Both properties are immutable, and their types are narrowed to their exact literal values.

Why Use Const Assertions?

Const assertions provide several benefits:

  1. Improved Type Safety: By narrowing types to their literal values, const assertions reduce the risk of unintended changes and make your code more predictable.

  2. Immutability: Const assertions enforce immutability, which is particularly useful in functional programming or when working with configuration objects.

  3. Better Autocompletion and Tooling: Since TypeScript knows the exact values, it can provide better autocompletion and type-checking in your editor.

  4. Simplified Redux and State Management: Const assertions are especially useful in Redux or other state management libraries, where actions and state are often defined as literal types.

Practical Use Cases

1. Redux Actions

Const assertions are commonly used in Redux to define action types:

const INCREMENT = "INCREMENT" as const;
const DECREMENT = "DECREMENT" as const;
Enter fullscreen mode Exit fullscreen mode

This ensures that the action types are treated as literal types, preventing typos and mismatches.

2. Configuration Objects

When defining configuration objects, const assertions ensure that the values cannot be modified:

const appConfig = {
  theme: "dark",
  features: {
    analytics: true,
    notifications: false,
  },
} as const;
Enter fullscreen mode Exit fullscreen mode

3. Enums Alternative

Const assertions can be used as an alternative to enums, providing similar benefits without the overhead of an enum:

const Status = {
  Pending: "Pending",
  Success: "Success",
  Failure: "Failure",
} as const;
Enter fullscreen mode Exit fullscreen mode

Limitations

While const assertions are powerful, they have some limitations:

  1. No Dynamic Values: Const assertions only work with values that are known at compile time. You cannot use them with dynamically computed values.

  2. Deep Immutability: While deep immutability is useful, it can sometimes be restrictive if you need to modify nested properties.

Conclusion

Const assertions in TypeScript are a powerful tool for improving type safety and enforcing immutability in your code. By narrowing types to their literal values and marking properties as readonly, const assertions help you write more predictable and maintainable code. Whether you’re working with Redux actions, configuration objects, or simply want to ensure immutability, const assertions are a valuable addition to your TypeScript toolkit.

Next time you find yourself defining constants or configuration objects, consider using as const to unlock the full potential of TypeScript’s type system!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay