无法正确键入函数返回函数

托梅克·布泽夫斯基

我是 TypeScript 的初学者。我有一个函数,它返回一个包含两个函数的对象,就这么简单。我已经为它定义了一个返回接口,但是由于某种原因,当我尝试使用返回的接口之一时,我得到了

TS2339:属性 'get' 不存在于类型 '() => { get: (url: string) => string | 空值; set: ({ url, body }: SetItemInterface) => void; }'。

这是代码:

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;

操场

我应该怎么办?

努博尔·阿尔皮斯巴耶夫

cache 是一个函数:

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

并且您通过尝试对其调用.get方法来将其视为对象

cache.get(...

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章