Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 无法正确键入函数返回函数_Typescript - Fatal编程技术网

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

Typescript 无法正确键入函数返回函数,typescript,Typescript,说到打字,我是个初学者。我有一个函数,它返回一个包含两个函数的对象,就这么简单。我已经为它定义了一个返回接口,但是由于某种原因,当我尝试使用其中一个返回接口时,我得到了 TS2339:类型“()=>{get:(url: string)=>string | null;set:({url,body}:SetItemInterface)=> void;} 代码如下: import * as Express from "express"; interface StorageInterface {

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

TS2339:类型“()=>{get:(url: string)=>string | null;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;


我该怎么办?

缓存是一种功能:

const cache = (): CacheFunctionInterface => { ...
通过尝试调用
.get
方法将其视为对象

cache.get(...

哦,天哪,你完全正确!这太简单了!谢谢!我会给出更有用/详细的答案,但是你的代码不够集中(代码太多,不确定你的意图),所以很难做到。不,不,不,你的答案是完美的。我只是忘记了
缓存是一个函数,我希望它是一个对象。调用它是使它全部工作的全部。