Ben Aston Ben Aston - 19 days ago 5
TypeScript Question

Memoizing a method on an object in TypeScript

In JS I'd do:

var o = {
foo: memoize(foo)
};


How do I do memoize an instance method in TypeScript similarly?

class C {
// How do I memoize this function?
public foo() :any {
}
}


I want to use a
class
to fit in with the idioms established in the existing TypeScript codebase.

Answer

Here are two ways to do it:

// With Typescript syntax
class C {
  foo = memoize(() => {
  });
}

// Using ES6-style initialization instead of field initializers
class C {
    foo: () => any;
    constructor() {
        this.foo = memoize(() => {
        });
    }
}