DEV Community

Vladimir
Vladimir

Posted on

TypeScript. How to add a property to class method?

I have next code:


export const getPath = async (from: CurrencyTicker, to: CurrencyTicker): Promise<ExchangePair[]> => {
  const helper = new Helper(from, to);
  const path = await helper.calculatePath()

  return path;
}
getExchangePath.cached = withMemoryCache('exchange-path', CACHE_PAIR_COUNT, ms('5m'), getExchangePath);

It works fine, but how can I make same thing with Class?

Something like that

class Estimate {
  private readonly helper: Helper;

  constructor(currencyFrom: CurrencyTicker, currencyTo: CurrencyTicker) {
    this.helper = new Helper(currencyFrom, currencyTo);

    // next line throws TS error Property 'cached' does not exist on type '() => Promise<[string, string][]>'
    this.getExchangePath.cached = withMemoryCache('exchange-path', CACHE_PAIR_COUNT, ms('5m'), getExchangePath);
  }

  getPath = async (): Promise<ExchangePair[]> => {
    const path = await this.helper.calculatePath()

    return path;
  }
}

Top comments (1)

Collapse
 
golubvladimir profile image
Vladimir Golub

Add interface

interface F { (): any; cached: number; }

class Estimate {
  ...

  getExchangePath = <F>function() {
    ...
  }
}
Enter fullscreen mode Exit fullscreen mode