github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/ui/src/util/nextState.ts (about)

     1  // Copyright 2018 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  import _ from "lodash";
    12  
    13  /**
    14   * nextState is a utility function that allows type-safe replacement of fields
    15   * when generating a new state in a redux reducer. This is an alternative to
    16   * using the spread operator; e.g. instead of:
    17   *
    18   * return {
    19   *   ...state,
    20   *   prop1: "newValue",
    21   * }
    22   *
    23   * nextState can be used instead:
    24   *
    25   * return nextState(state, {
    26   *   prop1: "newValue",
    27   * });
    28   *
    29   * The advantage is the explicit requirement that replacement values are
    30   * overwriting fields that exist on the type of state. In the examples above,
    31   * using the spread operator would compile even if "prop1" was not a field of
    32   * state's type. This is an explicit design choice of typescript.
    33   *
    34   * @param lastState An object representing the previous state of a reducer.
    35   * @param changes A set of new properties which should replace properties of the
    36   * previous object.
    37   */
    38  export default function nextState<T extends Object>(lastState: T, changes: Partial<T>): T {
    39      return _.assign({}, lastState, changes);
    40  }