Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 573
jlguenego Avatar asked Feb 17 '21 18:02

jlguenego


1 Answers

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"],
// ...
  },
// ...
}

like image 96
jlguenego Avatar answered Sep 22 '22 02:09

jlguenego