I've implemented a function for object memoization:
import memoizeOne from 'memoize-one';
type ArrayWithOneObj = [Record<string, unknown>];
const compareObject = ([obj1]: ArrayWithOneObj, [obj2]: ArrayWithOneObj) =>
obj1 === obj2 ||
(Object.keys(obj1).length === Object.keys(obj2).length &&
Object.keys(obj1).every(key => obj2.hasOwnProperty(key) && obj1[key] === obj2[key]));
const identity = (x: Record<string, unknown>) => x;
const memoizeObj = memoizeOne(identity, compareObject);
// USING IT:
type FruityObj = {
name: string;
};
const apple1: FruityObj = { name: 'apple' };
const apple2: FruityObj = { name: 'apple' };
// This works but the type of the memoized variables should be FruityObj instead
// of Record<string, unknown>
const memoizedApple1 = memoizeObj(apple1);
const memoizedApple2 = memoizeObj(apple2);
console.log(memoizedApple1 === memoizedApple2);
How can I modify it so that memoizeObj
returns the same type as passed in? I'm uncertain how to apply a Generic to memoizeObj
. Thanks!
Check out this runnable example: https://codesandbox.io/s/memoizeobj-bq3r8?file=/src/index.ts
Declaration of memoizeOne
:
export declare type EqualityFn = (newArgs: any[], lastArgs: any[]) => boolean;
export default function memoizeOne<ResultFn extends (this: any, ...newArgs: any[]) => ReturnType<ResultFn>>(resultFn: ResultFn, isEqual?: EqualityFn): ResultFn;