因此,我在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<{}>
,而不是应该返回的Promise<City>
。
失败的尝试:
- 我试图将返回对象包装在
Promise.resolve
中 - 我尝试使用
new Promise
,并依赖mongoose的回调API,而不是他们的承诺API
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)
};
}