因此,我在 node/express/mongoose 应用程序上使用 typescript,并且尝试对代码进行类型检查而不出现错误。
我定义了这个 Mongoose 模型:
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);
这个 Controller :
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<{}>
而不是Promise<City>
正如它应该的那样。
失败的尝试:
- 我尝试将返回对象包装在
Promise.resolve
中 - 我尝试使用
new Promise
并依赖 mongoose 的回调 API,而不是 Promise API
最佳答案
typescript resolves my 'getCityById' function as returning a Promise<{}> rather than a Promise as it should.
这是因为有多个返回路径。
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)
};
}
关于node.js - 如何使 typescript 与 promise 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36993170/