import type {Writable} from 'type-fest';
type Foo = {
readonly a: number;
readonly b: readonly string[]; // To show that only the mutability status of the properties, not their values, are affected.
readonly c: boolean;
};
const writableFoo: Writable<Foo> = {a: 1, b: ['2'], c: true};
writableFoo.a = 3;
// @ts-expect-error
writableFoo.b[0] = 'new value'; // Will still fail as the value of property "b" is still a readonly type.
writableFoo.b = ['something']; // Will work as the "b" property itself is no longer readonly.
type SomeWritable = Writable<Foo, 'b' | 'c'>;
// type SomeWritable = {
// readonly a: number;
// b: readonly string[]; // It's now writable. The type of the property remains unaffected.
// c: boolean; // It's now writable.
// }
// Also supports array
const readonlyArray: readonly number[] = [1, 2, 3];
// @ts-expect-error
readonlyArray.push(4); // Will fail as the array itself is readonly.
const writableArray: Writable<typeof readonlyArray> = readonlyArray as Writable<typeof readonlyArray>;
writableArray.push(4); // Will work as the array itself is now writable.
Create a type that strips
readonlyfrom the given type. Inverse ofReadonly<T>.The 2nd argument will be ignored if the input type is not an object.
Note: This type can make readonly
SetandMapwritable. This behavior is different fromReadonly<T>(as of TypeScript 5.2.2). See: https://github.com/microsoft/TypeScript/issues/29655This can be used to store and mutate options within a class, edit
readonlyobjects within tests, construct areadonlyobject within a function, or to define a single model where the only thing that changes is whether or not some of the keys are writable.