Tomek Buszewski
Tomek Buszewski

Reputation: 7935

Cannot properly type function returns functions

I am a beginner when it comes to TypeScript. I have a function that returns an object containing of two functions, simple as that. I've defined a return interface for it, but for some reason, when I try to use one of the returned, I am getting

TS2339: Property 'get' does not exist on type '() => { get: (url: string) => string | null; set: ({ url, body }: SetItemInterface) => void; }'.

Here's the code:

import * as Express from "express";

interface StorageInterface {
  [url: string]: {
    body: string;
    date: number;
  };
}

interface SetItemInterface {
  body: string;
  url: string;
}

interface ItemInterface {
  body: string;
  date: number;
}

interface CacheFunctionInterface {
  get(url: string): string | null;
  set(params: SetItemInterface): void;
}

const cache = (): CacheFunctionInterface => {
  const storage: StorageInterface = {};
  const cacheTime: number = 1000;

  /**
   * Creates or updates item in store.
   * @param {string} url
   * @param {string} body
   */
  const setItem = ({ url, body }: SetItemInterface): void => {
    storage.url = {
      body,
      date: Number(+new Date()) + cacheTime,
    };
  };

  /**
   * Gets the item if exists, otherwise null;
   * @param {string} url
   */
  const getItem = (url: string): string | null => {
    const item: ItemInterface = storage[url];
    const currentTime = +new Date();

    if (!!item) {
      if (item.date > currentTime) {
        return item.body;
      }
    }

    return null;
  };

  return {
    get: getItem,
    set: setItem,
  };
};

const cacheMiddleware = (req: Express.Request, res: Express.Response, next: Express.NextFunction) => {
  const { url }: { url: string } = req;
  const item: string | null = cache.get(url); // Here's the problem

  if (!!item) {
    return res.send(item);
  }

  return next();
};

export { cacheMiddleware };
export default cache;

and the playground.

What should I do?

Upvotes: 0

Views: 27

Answers (1)

Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21851

cache is a function:

const cache = (): CacheFunctionInterface => { ...

and you treat it as an object by trying to call .get method on it.

cache.get(...

Upvotes: 1

Related Questions