Learn TypeScript
Using `Object.freeze`
Using `Object.freeze`
In this lesson, we will explore how the JavaScript Object.freeze method can be used with TypeScripts' readonly` modifier to create immutable objects and arrays at both runtime and compile-time.
Using Object.freeze on arrays
Object.freeze is a JavaScript method that can make objects and arrays immutable at runtime. We are going to explore this along with TypeScript's readonly modifier in the TypeScript playground.
- Open the TypeScript playground by clicking the link below:
- Paste the code from below into the TypeScript playground:
let billScores = Object.freeze([90, 65, 80]);The code creates a frozen array.
What is the inferred type of billScores?
- Let's try to add an array item to
billScores:
billScores.push(100);Does a type error occur on this line of code?
- Output
billScoresto the console at the end of the code:
console.log(billScores);- Click the Run option in the TypeScript Playground and open the console.
Did the changes to the billScores array take place at runtime?
Nice!
- Clear the code from the TypeScript Playground, ready for the next section.
Using Object.freeze on objects
- Let's add a simple object with a type to the TypeScript Playground:
let bill = Object.freeze({ name: "Bill", age: 30,});The code creates a frozen object.
What is the inferred type of bill?
- Let's try to change an
ageonbill:
bill.age = 31;Does a type error occur on this line of code?
- Output
billto the console at the end of the code:
console.log(bill);- Click the Run option in the TypeScript Playground and open the console.
Did the changes to the age property take place at runtime?
Neat!
- Add the following additional properties to the
billobject:
let bill = Object.freeze({ ... scores: [90, 65, 80], profile: { level: 1 }});- Remove the assigment to
bill.ageand add the following assignments just before theconsole.logstatement:
bill.scores.push(100);bill.profile.level = 2;Does a type error occur on these lines of code?
- Click the Run option in the TypeScript and open the console.
Did the changes to the scores and level properties take place at runtime?
Object.freezeperforms a shallow freeze on an object.
Summary
Object-freeze with the readonly modifier allows us to create immutable arrays and objects at runtime and compile-time. It is important to note that Object.freeze only performs a shallow freeze.
In the next lesson, we will learn how to implement readonly function parameters.