我得到了一个错误,我只能通过添加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>,那么这个错误就会消失,但这显然不是我想要做的。我如何修复这个lint错误?
问题在函数声明中。您需要将返回类型指定为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); }};
typescript中的异步函数返回promise值。
如下所示:
export const dbConnections: any = {};export const connectDb: () => Promise<void> = async () => { ...};