Learn TypeScript

Introduction

Introduction

Immutable Types

In this module, we are going to learn how to create immutable types. Immutable types help prevent bugs due to unexpected side effects. Consider the following code:

function doubleScores(scores: number[]) {
scores.forEach((score, i) => (scores[i] = score * 2));
return scores;
}
const scores = [90, 65, 80];
const scoresDoubled = doubleScores(scores);
// ❗ scores has been unexpectedly changed
console.log(scores);

The doubleScores function mutates the parameter passed into it. The problem here is that the function's consumer wouldn't necessarily expect this to be the case and use scores later in the program, expecting it to have the original scores rather than the doubled scores. If the scores parameter had an immutable type, the TypeScript type checker would have flagged this up as a problem.

Immutable types also facilitate change tracking, which is essential in libraries like React. In React, a component is rerendered when its state changes.

Consider the following code:

type Person = {
name: string;
score: number;
};
export default function App() {
const [person] = React.useState<Person>({ name: "Bill", score: 7 });
return (
<div className="App">
<span>{person.name}</span>
<button onClick={() => (person.score += 1)}>{person.score}</button>;
</div>
);
}

When the button is clicked, the score is incremented. However, the change isn't reflected in the UI because the component isn't rerendered. This is because the person objects reference hasn't changed because it was mutated. If Person was an immutable type, the TypeScript type checker would have flagged this up as a problem.

In this module we will cover:

© 2020 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more