score:3

the following worked for me but i'm not sure if it's the best way.

import {
  createselectorcreator,
  defaultmemoize,
} from 'reselect';

type icomment = { id: number };
type state = { comments: icomment[] };
type comparefn = <t>(a: t, b: t, index: number) => boolean;
const createcustomequalselector = (equalfn: comparefn) =>
  createselectorcreator(defaultmemoize, equalfn);
const selectcomments = (state: state) => state.comments;
const commentsequalfn: comparefn = (a, b, index) =>
  //need to cast it or get an error:
  //  property 'length' does not exist on type 't'
  ((a as unknown) as icomment[]).length ===
  ((b as unknown) as icomment[]).length;

export const selectemailsfromcomments = createcustomequalselector(
  commentsequalfn
)(
  selectcomments, // returns an array of comments
  (comments) => {
    console.log('calculating comments:', comments);
    return comments;
  }
);
selectemailsfromcomments({ comments: [{ id: 1 }] })
//this will log previous value because array length didn't change
console.log('memoized', selectemailsfromcomments({ comments: [{ id: 2 }] }))

Related Query

More Query from same tag