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:

Integrating Django Templates With React For Dynamic Webpages

Integrating Django templates with React for dynamic webpages

Create a dynamic demo blog site using Django and React to demonstrate Django’s server-side functionalities and React’s interactive UI.

Kayode Adeniyi
Apr 18, 2024 â‹… 7 min read
Using Aoi Js To Build A Bot For Discord

Using aoi.js to build a bot on Discord

Explore how the aoi.js library makes it easy to create Discord bots with useful functionalities for frontend applications.

Rahul Padalkar
Apr 17, 2024 â‹… 9 min read
Web Components Adoption Guide: Overview, Examples, And Alternatives

Web Components adoption guide: Overview, examples, and alternatives

Evaluate Web Components, a set of standards that allow you to create custom HTML tags for more reusable, manageable code.

Elijah Asaolu
Apr 16, 2024 â‹… 11 min read
Using Aws Lambda And Aws Cloudfront To Optimize Image Handling

Using AWS Lambda and CloudFront to optimize image handling

Leverage services like AWS Lambda, CloudFront, and S3 to handle images more effectively, optimizing performance and providing a better UX.

Nitish Sharma
Apr 12, 2024 â‹… 12 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