paint-brush
"as const" — Typescript's Unsung Hero for Strongly Typed Variables by@todayscode14
172 reads

"as const" — Typescript's Unsung Hero for Strongly Typed Variables

by Today's CodeOctober 19th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Md Taqui imam is a Full Stack web developer. He is the author of "A Cool TypeScript Feature You Might Not Know About: as const" As const is a way to make type checks stricter by preventing certain operations on a value. By adding it, we make TypeScript treat the array in a more "specific" way.
featured image - "as const" — Typescript's Unsung Hero for Strongly Typed Variables
Today's Code HackerNoon profile picture


Table of contents

  • Here are some examples of "as const" :

  • Enum Types

  • Tuple Types

  • Function Return Types

  • Object Properties

    • Conclusion✨
    • Happy Coding 😊




Have you ever worked with types in TypeScript and found yourself wanting more control over how those types behave? Well, there's a handy little feature called as const that can help with that.


as const is a way to make type checks stricter by preventing certain operations on a value. For example, let's say we have an array:


const fruits = ['apple', 'banana', 'orange'];


By default, TypeScript sees this as an array that can contain any string. But what if we wanted TypeScript to know that this array will only ever contain these three specific string values?


That's where as const comes in. By adding it, we make TypeScript treat the array in a more "specific" way:


const fruits = ['apple', 'banana', 'orange'] as const;


Now, instead of just being a string[], fruits are seen as the specific tuple type ['apple', 'banana', 'orange'].


This means TypeScript will give us errors if we try to add or remove items from the array. It knows the values are "locked in". as const works on other types too.



For example, you could mark an object as constant to prevent adding or removing properties:

interface Cat {
  name: string;
  age: number;
}

const garfield = {
  name: 'Garfield', 
  age: 10
} as const;


Now Garfield is seen as an object with very specific fields, rather than a loose Cat interface.


Here are some examples of "as const" in action

Here are some more examples of how as const can be used in TypeScript:

Enum Types

You can make an enum as const to remove the implicit number types:

enum Colors {
  Red,
  Green,
  Blue
}

let c = Colors.Green; // number

enum ColorsAsConst {
  Red, 
  Green,
  Blue
} as const;

let c = ColorsAsConst.Green; // ColorsAsConst.Green


Tuple Types

Mark a tuple as const to make its types very specific:

let tuple = [1, 'two'] as const;

tuple[0].toFixed(); // OK
tuple[1].toLowerCase(); // OK


Function Return Types

Mark a function return value as const to narrow its type:

function createError() {
  return {message: 'an error'} as const;
}

const err = createError();
err.message = 'something else'; // Error


Object Properties

Objects marked as const prevent adding/removing properties:

interface Point {
  x: number;
  y: number;
}

const p = {x: 0, y: 0} as const; 

p.z = 0; // Error

So in summary, as const brings immutability and more precise types to enums, tuples, return values, objects, and more!


Conclusion✨

In summary, const proves to be a clever tool for enforcing stricter and more specific types in TypeScript. It serves as a clear communication of your intent when you require values to remain immutable. Don't hesitate to implement it in your upcoming projects!


Thank you for Reading this article💖


Also published here.