You can create a "mutable" utility type in the following way:
// TypeScript 2.8+ type Mutable<T> = { -readonly [P in keyof T]: T[P] };
This would allow you to make properties declared as readonly
to be writable by stripping off the readonly
modifier from them. For example:
// TypeScript 2.8+ type Mutable<T> = { -readonly [P in keyof T]: T[P] }; interface Person { readonly name: string; readonly age: number; } const person: Mutable<Person> = { name: 'John Doe', age: 24 }; person.age = 37;
The custom Mutable<T>
utility type works because of the "-
" prefix added to the readonly
modifier (i.e. -readonly
), which means that the readonly
modifier is removed from a mapped type, making all properties mutable. Without the Mutable<T>
type, this would throw an error if you try to reassign values of a type that's declared as readonly
:
// TypeScript 2.8+
interface Person {
readonly name: string;
readonly age: number;
}
const person: Person = { name: 'John Doe', age: 24 };
// Error: Cannot assign to 'age' because it is a read-only property.
person.age = 37;
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.