Skip to content

Latest commit

 

History

History
143 lines (113 loc) · 5.86 KB

values-in-sync.md

File metadata and controls

143 lines (113 loc) · 5.86 KB

Item 61: Use Record Types to Keep Values in Sync

Things to Remember

  • Recognize the fail open versus fail closed dilemma.
  • Use ++Record++ types to keep related values and types synchronized.
  • Consider using ++Record++ types to force choices when adding new properties to an interface.

Code Samples

interface ScatterProps {
  // The data
  xs: number[];
  ys: number[];

  // Display
  xRange: [number, number];
  yRange: [number, number];
  color: string;

  // Events
  onClick?: (x: number, y: number, index: number) => void;
}

💻 playground


function shouldUpdate(
  oldProps: ScatterProps,
  newProps: ScatterProps
) {
  for (const kStr in oldProps) {
    const k = kStr as keyof ScatterProps;
    if (oldProps[k] !== newProps[k]) {
      if (k !== 'onClick') return true;
    }
  }
  return false;
}

💻 playground


function shouldUpdate(
  oldProps: ScatterProps,
  newProps: ScatterProps
) {
  return (
    oldProps.xs !== newProps.xs ||
    oldProps.ys !== newProps.ys ||
    oldProps.xRange !== newProps.xRange ||
    oldProps.yRange !== newProps.yRange ||
    oldProps.color !== newProps.color
    // (no check for onClick)
  );
}

💻 playground


interface ScatterProps {
  xs: number[];
  ys: number[];
  // ...
  onClick?: (x: number, y: number, index: number) => void;

  // Note: if you add a property here, update shouldUpdate!
}

💻 playground


const REQUIRES_UPDATE: Record<keyof ScatterProps, boolean> = {
  xs: true,
  ys: true,
  xRange: true,
  yRange: true,
  color: true,
  onClick: false,
};

function shouldUpdate(
  oldProps: ScatterProps,
  newProps: ScatterProps
) {
  for (const kStr in oldProps) {
    const k = kStr as keyof ScatterProps;
    if (oldProps[k] !== newProps[k] && REQUIRES_UPDATE[k]) {
      return true;
    }
  }
  return false;
}

💻 playground


interface ScatterProps {
  // ...
  onDoubleClick?: () => void;
}

💻 playground


const REQUIRES_UPDATE: Record<keyof ScatterProps, boolean> = {
  //  ~~~~~~~~~~~~~~~ Property 'onDoubleClick' is missing in type ...
  // ...
};

💻 playground


const PROPS_REQUIRING_UPDATE: (keyof ScatterProps)[] = [
  'xs',
  'ys',
  // ...
];

💻 playground