2023-03-09
1696
#typescript
Paul Cowan
2066
Mar 9, 2023 â‹… 6 min read

A complete guide to const assertions in TypeScript

Paul Cowan Contract software developer.

Recent posts:

Using React Shepherd To Build A Site Tour

Using React Shepherd to build a site tour

React Shepherd stands out as a site tour library due to its elegant UI and out-of-the-box, easy-to-use React Context implementation.

Onuorah Bonaventure
May 1, 2024 â‹… 14 min read
A Guide To Cookies In Next Js

A guide to cookies in Next.js

Cookies are crucial to web development. This article will explore how to handle cookies in your Next.js applications.

Georgey V B
Apr 30, 2024 â‹… 10 min read
Handling Dates In JavaScript With Tempo

Handling dates in JavaScript with Tempo

Use the Tempo library to format dates and times in JavaScript while accounting for time zones, daylight saying time, and date internationalization.

Amazing Enyichi Agu
Apr 30, 2024 â‹… 8 min read
A Guide To Deno.cron

A guide to Deno.cron

This guide explores how to use the cron package in Deno, `Deno.cron`, to handle scheduling tasks with specific commands.

Rosario De Chiara
Apr 29, 2024 â‹… 5 min read
View all posts

5 Replies to "A complete guide to <code>const</code> assertions in TypeScript"

  1. The example in your conclusion is wrong: z and a would not be read-only since those are the keys for nested object. This is currently the behavior of “as const” syntax.

  2. that isn’t true, this is the resultant type:

    “`
    let obj: {
    readonly x: 10;
    readonly y: readonly [20, 30];
    readonly z: {
    readonly a: {
    readonly b: 42;
    };
    };
    }
    “`
    and this error happens when you try to modify z o a
    “`
    Cannot assign to ‘z’ because it is a read-only property.(2540)
    “`

  3. The example with redux actions is striking. With interfaces it’s clear and reads nicely, with ‘const’ assertion, it becomes more…implicit and easier to overlook. IMO interfaces are better for this purpose. The goal is not to write maintainable code, not as little code as possible.
    But the purpose of the assertion is clear when it comes to literals.
    Nice article, thanks!

Leave a Reply