Home > Blockchain >  Javascript equivalent of Typescript const assertion
Javascript equivalent of Typescript const assertion

Time:12-09

What is the javascript equivalent for typescript's const assertion?

const arr = [1,2,3,4] as const

I want to achieve this array in javascript to avoid further mutation.

CodePudding user response:

Yes, Use Object.freeze

const arr = [1, 2, 3, 4, 5];
Object.freeze(arr);

arr.push(8); // Uncaught TypeError: Cannot add property 5, object is not extensible

CodePudding user response:

Anil kumar's answer is also good. One piece of advice: There are also similar but different types of seal methods. I don't know what you need, so I leave a link

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal

  • Related