Search code examples
typescriptweak-references

How to use WeakRef in Typescript?


I want to use WeakRef in Typescript. I tried using the last version available at the moment (4.1.5). I have a compilation error:

const toIdString = (o: Object): string =>
  o.constructor.name + JSON.stringify(o);

export class MemoCache {
  static handle<T>(o: T): T {
    const id = toIdString(o);
    const cached = MemoCache.map.get(id);
    if (cached) {
      return cached.deref() as T;
    }
    MemoCache.map.set(id, new WeakRef(o));
    return o;
  }

  static map = new Map<string, WeakRef>();
}

I have compilation errors.


src/Memoizer.ts:11:31 - error TS2304: Cannot find name 'WeakRef'.

11     MemoCache.map.set(id, new WeakRef(o));
                                 ~~~~~~~

src/Memoizer.ts:15:32 - error TS2304: Cannot find name 'WeakRef'.

15   static map = new Map<string, WeakRef>();
                                  ~~~~~~~

However, this is ECMAScript 2021. Chrome 88 seems to understand it. I have node 15.8.0 (the last one) Do you have any idea how to make Typescript understand WeakRef ?


Solution

  • On the 18 Feb 2021, in order to use WeakRef in Typsecript, you need to have and configure tsconfig.json by adding ESNext to the lib property.

    {
      "compilerOptions": {
    // ...
        "lib": ["ESNext"],
    // ...
      },
    // ...
    }