我遇到一个错误,只能通过添加any
作为返回值来解决。
export const dbConnections: any = {};
export const connectDb: Promise<void> = async () => {
if (dbConnections.isConnected) {
return;
}
try {
const db = await mongoose.connect(config.get('mongoURI'), {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
});
dbConnections.isConnected = db.connections[0].readyState;
} catch (err) {
createError('Error caught connecting to db!', err);
}
};
这会引发错误,
export const connectDb: Promise<void> = async () => {
^^^^^^^^^^^^^
Type '() => Promise<void>' is missing the following properties
from type 'Promise<void>': then, catch, [Symbol.toStringTag], finally
如果我使用any
而不是Promise<void>
,则错误消失了,但这显然不是我要解决的方法。如何解决此皮棉错误?
答案 0 :(得分:0)
问题在函数声明中。您需要将返回类型指定为Promise<void>
。
export const connectDb = async (): Promise<void> => {
if (dbConnections.isConnected) {
return;
}
try {
const db = await mongoose.connect(config.get('mongoURI'), {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
});
dbConnections.isConnected = db.connections[0].readyState;
} catch (err) {
createError('Error caught connecting to db!', err);
}
};
答案 1 :(得分:0)
打字稿中的异步函数是返回承诺值的函数。 您可以这样定义函数类型:
export const dbConnections: any = {};
export const connectDb: () => Promise<void> = async () => {
...
};