【问题标题】:Cannot properly type function returns functions无法正确键入函数返回函数
【发布时间】:2019-03-25 04:09:01
【问题描述】:

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

TS2339:类型 '() => { get: (url: 字符串)=> 字符串 |空值;设置: ({ url, body }: SetItemInterface) => 空白; }'。

代码如下:

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;

the playground

我该怎么办?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    cache 是一个函数:

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

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

    cache.get(...
    

    【讨论】:

    • 天哪,你完全正确!这太简单了!非常感谢!
    • 我会做出更有用/更详细的答案,但是您的代码不够集中(大量代码,不确定您的意图是什么),因此很难做到。
    • 不,不,不,你的答案是完美的。我只是忘记了cache 是一个函数,我希望它是一个对象。调用它就可以让它全部工作。
    猜你喜欢
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 2018-02-07
    • 2016-01-03
    • 1970-01-01
    相关资源
    最近更新 更多