【问题标题】:How do I make typescript work with promises?如何使 typescript 与 Promise 一起使用?
【发布时间】:2016-08-27 20:26:15
【问题描述】:

所以,我在 node/express/mongoose 应用程序上使用 typescript,我试图让我的代码类型检查没有错误。

我定义了这个猫鼬模型:

import * as mongoose from 'mongoose';

const City = new mongoose.Schema({
  name: String
});

interface ICity extends mongoose.Document {
  name: string
}

export default mongoose.model<ICity>('City', City);

还有这个控制器:

import * as Promise from 'bluebird';

import CityModel from '../models/city';

export type City = {
  name: string,
  id: string
};

export function getCityById(id : string) : Promise<City>{
  return CityModel.findById(id).lean().exec()
  .then((city) => {
    if (!city) {
      return Promise.reject('No Cities found with given ID');
    } else {
      return {
        name: city.name,
        id: String(city._id)
      };
    }
  });
}

问题在于,由于某种原因,typescript 将我的“getCityById”函数解析为返回 Promise&lt;{}&gt; 而不是应该返回的 Promise&lt;City&gt;

尝试失败:

  • 我尝试将返回对象包装在Promise.resolve
  • 我尝试使用 new Promise 并依赖 mongoose 的回调 API,而不是他们的 Promise API

【问题讨论】:

  • 可能是因为在一个分支中您返回 Promise 而在另一个分支中返回 City 并且当编译器尝试推断类型时,函数返回它可以对这两个执行的最佳操作是空对象。
  • 不,我试图删除返回承诺的分支,但我仍然得到同样的错误
  • 此外,我尝试将城市包装在一个承诺中......同样的错误
  • 是的,对不起,错过了您问题中的那一部分。你试过.then&lt;City&gt;(...)吗?
  • 如果您查看定义文件,您会发现then 方法具有泛型签名。编译器应该已经推断出类型而无需显式编写它,但它没有这样做,不知道为什么。在任何情况下,通过指定类型,您可以告诉编译器在生成的Promise 中包含哪种类型

标签: node.js mongoose typescript promise bluebird


【解决方案1】:

typescript 将我的“getCityById”函数解析为返回 Promise 而不是应有的 Promise。

这是因为有多个返回路径。

if (!city) {
      return Promise.reject('No Cities found with given ID');
    } else {
      return {
        name: city.name,
        id: String(city._id)
      };
    }

特别是Promise.reject 是无类型的。

快速修复

断言:

if (!city) {
      return Promise.reject('No Cities found with given ID') as Promise<any>;
    } else {
      return {
        name: city.name,
        id: String(city._id)
      };
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 2020-04-16
    • 2020-04-04
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多