alexreardon / memoize-one

A memoization library which only remembers the latest invocation
MIT License
2.94k stars 78 forks source link

TypeScript errors with modules #267

Open joshkel opened 4 months ago

joshkel commented 4 months ago

According to Are the Types Wrong, memoize-one has an incorrect default export.

This can cause errors with TypeScript, depending on tsconfig.json settings. For example:

As I understand it, there are two possible solutions:

  1. Hand-write a .d.ts file that reflects the CommonJS export assignment approach used by the Rollup-generated memoize-one build. (There may be a way to get tsc to do this for you, but I haven't been able to figure it out.) I believe that this could be done in a semver-patch release.
declare namespace memoizeOne {
    export type EqualityFn<TFunc extends (...args: any[]) => any> = (newArgs: Parameters<TFunc>, lastArgs: Parameters<TFunc>) => boolean;
    export type MemoizedFn<TFunc extends (this: any, ...args: any[]) => any> = {
        clear: () => void;
        (this: ThisParameterType<TFunc>, ...args: Parameters<TFunc>): ReturnType<TFunc>;
    };
}
declare function memoizeOne<TFunc extends (this: any, ...newArgs: any[]) => any>(
    resultFn: TFunc, isEqual?: memoizeOne.EqualityFn<TFunc>
): memoizeOne.MemoizedFn<TFunc>;
export = memoizeOne;
  1. Add full-fledged module support: update memoize-one's package.json to export its ESM build via exports (so Node.js, and TypeScript when using node16 module resolution, can see it), with ESM-specific types. This may be a semver-major change.

If you're interested in one of these approaches, I can try and open a PR.

alexreardon commented 4 months ago

I think it's time to do something to make memoize-one have a fantastic esm story

alexreardon commented 4 months ago

How do you feel about an approach like this? (It's from a WIP package i've been working on)

https://github.com/alexreardon/limit-once/blob/main/package.json#L20-L25

Codex- commented 2 months ago

How do you feel about an approach like this? (It's from a WIP package i've been working on)

https://github.com/alexreardon/limit-once/blob/main/package.json#L20-L25

Very reasonable imo

Ran into this exact issue today when trying to move some services to esm