Guest User

Untitled

a guest
Sep 19th, 2019
87
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. ```
RAW Paste Data