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>;

  • 相关阅读:
    自学MongoDB(1)
    小心心
    js文件处理File
    jquery图片滚动jquery.scrlooAnimation.js
    jquery图片滚动normalizy.css
    jquery图片滚动demo.css
    jquery图片滚动animate.css
    jquery图片滚动
    C# 数组与集合的区别
    SQL server 批量插入和更新数据
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10321465.html
Copyright © 2011-2022 走看看