Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- TS原生的Readonly只会限制一层写入操作,我们可以利用递归来实现深层次的Readonly。但要注意,TS对最大递归层数做了限制,最多递归5层。
- ```
- type DeepReadony<T> = {
- readonly [P in keyof T]: DeepReadony<T[P]>
- }
- interface SomeObject {
- a: {
- b: {
- c: number;
- };
- };
- }
- const obj: Readonly<SomeObject> = { a: { b: { c: 2 } } };
- obj.a.b.c = 3; // TS不会报错
- const obj2: DeepReadony<SomeObject> = { a: { b: { c: 2 } } };
- obj2.a.b.c = 3; // Cannot assign to 'c' because it is a read-only property.
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement