JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

Object Mutation vs TypeScript: Why You Should Avoid Object Mutation

--

We use TypeScript to make assumptions on what a variable contains and when a code is well-typed we trust it blindly, as we are supposed to.

But there are some cases where mutation breaks typing, like the following case

type Animal =
| {
name: 'cat';
noise: 'meow';
}
| {
name: 'dog';
noise: 'woof';
};

const fn = (animal: Animal) => {
// Typescript still considers this to be of type 'Animal'
// after this mutation, even though its value no longer assignable to any variant of Animal.
animal.noise = 'woof';

// ❌ - Typescript failed to update animal's type when we mutated it, so now
// it mistakenly continues to believe it is assignable to Animal everywhere!
// Now its incorrectly typed data can spread throughout the application,
// breaking type safety, potentially everywhere...
const anotherAnimal: Animal = animal;

// ✅ - Typescript correctly prevents us from assigning this combination of fields
// to type Animal. But this is exactly the value we mutated to in our first example
const animalMatchingPostMutationValue: Animal = {
name: 'cat',
noise: 'woof',
};
};

const animal: Animal = {
name: 'cat',
noise: 'meow',
};

fn(animal);

That’s why mutation should be avoided, typescript has no way of preventing such a bug, and you will spend hours trying to debug it.

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

Sign up to discover human stories that deepen your understanding of the world.

--

--

No responses yet

Write a response