1

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.

6
  • What's the intent of changing it into a class? Just because you're using TS doesn't mean you have to convert everything to classes. Write the JS you would have written anyway, and add type annotations where you want. Commented Nov 17, 2016 at 20:24
  • Can you return arbitrary objects from typescript class constructors? I ask because this is not my codebase and I need to leverage the Angular injector. Everytime I try and do something in TS I run into an unanticipated roadblock. Commented Nov 17, 2016 at 20:25
  • What does TS have to do with this? Classes are an ES6 feature. Commented Nov 17, 2016 at 20:28
  • This is a typescript codebase. Presumably I have to therefore write in TS. Or at the very least if I don't then I have to dodge the type errors and I am unsure if I know how to do that. Commented Nov 17, 2016 at 20:29
  • TypeScript is a superset of JavaScript... Commented Nov 17, 2016 at 20:30

1 Answer 1

2

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(() => {
        });
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.