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:
- Be sure to clap and follow the writer ️👏️️
- Follow us: X | LinkedIn | YouTube | Discord | Newsletter
- Visit our other platforms: Stackademic | CoFeed | Venture | Cubed
- More content at PlainEnglish.io