Skip to content

Instantly share code, notes, and snippets.

@librz
Created April 16, 2024 11:51
Show Gist options
  • Save librz/c7174c6c84d7aacf9670ceb32047ec21 to your computer and use it in GitHub Desktop.
Save librz/c7174c6c84d7aacf9670ceb32047ec21 to your computer and use it in GitHub Desktop.
`as const` except in js

In TypeScript, u can easily declare constants using as const:

const Meal = {
  Breakfast: 'breakfast',
  Lunch: 'lunch',
  Dinner: 'dinner'
}

If u are limited to JavaScript, here's 2 solutions:

  1. using Object.freeze
const Meal = Object.freeze({
  Breakfast: 'breakfast',
  Lunch: 'lunch',
  Dinner: 'dinner'
})

This introduces runtime restriction though.

  1. using JSDoc /** @type {const} */
const Meal = /** @type {const} */ ({
  Breakfast: 'breakfast',
  Lunch: 'lunch',
  Dinner: 'dinner'
})

see: https://stackoverflow.com/questions/64559624/jsdoc-equivalent-to-typescripts-as-const

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment