It is possible to create a DeepReadonly
type like this:
type DeepReadonly<T> = {
readonly [P in keyof T]: DeepReadonly<T[P]>;
};
interface A {
B: { C: number; };
D: { E: number; }[];
}
const myDeepReadonlyObject: DeepReadonly<A> = {
B: { C: 1 },
D: [ { E: 2 } ],
}
myDeepReadonlyObject.B = { C: 2 }; // error :)
myDeepReadonlyObject.B.C = 2; // error :)
This is great. Both B
and B.C
are readonly. When I try to modify D
however...
// I'd like this to be an error
myDeepReadonlyObject.D[0] = { E: 3 }; // no error :(
How should I write DeepReadonly
so that nested arrays are readonly as well?
console.log(myDeepReadonlyObject.D[0]);
Which version of typescript are you using? – LoraineDeepReadonly
is part ofts-essentials
package. Check it out: github.com/krzkaczor/ts-essentials – Issacissachar