Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.56 KB | None | 0 0
  1. TS原生的Readonly只会限制一层写入操作,我们可以利用递归来实现深层次的Readonly。但要注意,TS对最大递归层数做了限制,最多递归5层。
  2. ```
  3. type DeepReadony<T> = {
  4. readonly [P in keyof T]: DeepReadony<T[P]>
  5. }
  6.  
  7. interface SomeObject {
  8. a: {
  9. b: {
  10. c: number;
  11. };
  12. };
  13. }
  14.  
  15. const obj: Readonly<SomeObject> = { a: { b: { c: 2 } } };
  16. obj.a.b.c = 3; // TS不会报错
  17.  
  18. const obj2: DeepReadony<SomeObject> = { a: { b: { c: 2 } } };
  19. obj2.a.b.c = 3; // Cannot assign to 'c' because it is a read-only property.
  20.  
  21. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement