DEV Community

Tomasz Kudlinski
Tomasz Kudlinski

Posted on

6

'as const' in Typescript, better constant object support in IDE

In most projects we have some kind of global config object. You may store there urls to API endpoints, constant string values, default values of parameters for some external scripts/services etc.

Example of the global config object:

const config = {
  a: 84595,
  b: 'some string',
  c: {
    items: ['item1', 'item2', 'item3'],
  },
}

If you are using Typescript in your project with modern IDE (like Visual Studio Code), you will get below feedback from it:

const config: {
    a: number;
    b: string;
    c: {
        items: string[];
    };
}

This feedback is already useful. While working on your code and accessing your config you will know that config.c.items is an array of strings, but you can get much more almost for free! Check below code:

const config = {
  a: 84595,
  b: 'some string',
  c: {
    items: ['item1', 'item2', 'item3'],
  },
} as const

The only difference in this piece of code is the as const added after the object definition. It will give you below feedback from IDE:

const config: {
    readonly a: 84595;
    readonly b: "some string";
    readonly c: {
        readonly items: readonly ["item1", "item2", "item3"];
    };
}

Now you see exactly what value is stored under each property of the global config object.

Tiugo image

Fast, Lean, and Fully Extensible

CKEditor 5 is built for developers who value flexibility and speed. Pick the features that matter, drop the ones that don’t and enjoy a high-performance WYSIWYG that fits into your workflow

Start now

Top comments (1)

Collapse
 
dgreene1 profile image
Dan Greene

Hi @tkudlinski , I decided to throw you some attention by linking to your article instead of linking to Microsoft's article. I figure why not help eachother since we're all in the dev.to family. :)

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay