zoukankan      html  css  js  c++  java
  • [TypeScript] Deeply mark all the properties of a type as read-only in TypeScript

    We will look at how we can use mapped types, conditional types, self-referencing types and the “infer” keyword to create a reusable generic type that traverses down the properties of an object and marks of all them as read-only. This is especially useful when used with Redux, to ensure our whole state tree is marked as read-only and immutable.

    For example we have complex interface:

    interface IRootState {
      userId: string;
      showCompletedOnly: boolean;
      todoTypes: string[];
      todos: ITodo[];
      iconGrid: string[][];
    }
    
    interface IEmail {
      from: string;
      to: string[];
      body: string;
    }
    
    interface ITodo {
      isCompleted: boolean;
      text: string;
      linkedEmail: IEmail;
    }

    If we want to add readonly to all the props of IRootState. We want to do it automaticlly.

    type DeepReadonlyObject<T> = { readonly [K in keyof T]: DeepReadonly<T[K]> };
    
    type DeepReadonly<T> = T extends (infer E)[] ?
      ReadonlyArray<DeepReadonlyObject<E>> :
      T extends object ? DeepReadonlyObject<T> :
        T;
    type IReadonlyRootState = DeepReadonly<IRootState>;

  • 相关阅读:
    Vue数组循环
    vue使用swiper6分页器踩坑
    Vue基础语法(四)
    Vue安装jquery
    Vue基础语法(三)
    Too Rich(贪心加搜索)
    ZOJ Anagrams by Stack(堆栈中的搜索)
    最长子序列和(分治法实现)
    幸运数字(数位dp)
    蜥蜴和地下室(深搜)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10321465.html
Copyright © 2011-2022 走看看