DEV Community

loading...

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

Tomasz Kudlinski
Fullstack Engineer #react #typescript #node.js #react-native #redux #graphql #apollo
・1 min read

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.

Discussion (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. :)