如何在TypeScript中键入node-postgres异步查询函数? [英] How to type node-postgres async query functions in TypeScript?
问题描述
我对TypeScript相当陌生,并开始将现有服务器从ES6转换为TypeScript.我有点迷茫,试图弄清楚如何为异步函数声明类型.这是ES6代码的存根:
I am fairly new to TypeScript and started to convert my existing server from ES6 to TypeScript. I am a bit lost and trying to figure out how to declare types for async functions. Here's a stub from the ES6 code:
// db.js
import { Pool } from 'pg';
const pool = new Pool({
connectionString: 'process.env.DB_CONNECTION',
});
export default {
query(text, params) {
return new Promise((resolve, reject) => {
try {
const result = pool.query(text, params);
return resolve(result);
} catch (error) {
return reject(error);
}
});
},
};
// controller for a table
const Table = {
getOne: async (id) => {
return await db.query('SELECT * FROM table WHERE id=$1', [id]);
},
}
这很好用,可以通过消耗try/catch块中的一部分来处理,并且无论查询返回结果还是错误都可以使用.现在我该如何在打字稿中键入这些内容?我尝试这样做:
This works fine and could be processed by consuming part in a try/catch block and it works whether the query returns a result or an error. Now how should I type these in typescript? I tried doing this:
import { Pool } from 'pg';
const pool = new Pool({
connectionString: 'process.env.DB_CONNECTION',
});
export default {
query(text: string, params: any[]) {
return new Promise((resolve, reject) => {
try {
const result = pool.query(text, params);
return resolve(result);
} catch (error) {
return reject(error);
}
});
},
};
// controller
import { QueryResult } from 'pg';
const Table = {
getOne: async (id: string) => {
return await db.query('SELECT * FROM table WHERE id=$1', [id]) as QueryResult;
},
}
现在,可以编译了,但是有一些我没有得到的东西.首先,始终将这些返回类型转换为'as'是非常多余的.我不应该能够像这样getOne: async (id: string): Promise<QueryResult> => {...}
那样声明返回类型吗?那么,如果诺言被拒绝,会发生什么呢?那不再是QueryResult类型.我已经尝试阅读有关node-postgres和TypeScript函数类型声明的文档,但是却一无所获.我应该怎么做?也可能我也应该开始学习声明文件.
Now, this compiles, but there are couple things I don't get. First, it is quite redundant to always cast these return types with 'as'. Shouldn't I be able to declare the return type somehow like this getOne: async (id: string): Promise<QueryResult> => {...}
? Then, what would happen, if the promise rejected? That isn't a QueryResult type anymore afaik. I have tried to read the documentations about node-postgres and TypeScript function type declarations, but I am getting nowhere. How I should do these? Also probably I should start learning declaration files too.
推荐答案
异步函数隐式返回promise
async functions implicitly return promises
示例:
// Declare async function
async function getRandomNumberAsync(max: number): Promise<number> {
return Math.floor(Math.random() * Math.floor(max));
}
// Call it (errors are handled with a try/catch)
try {
const result = await getRandomNumberAsync(100);
console.log(result);
} catch (e) {
console.error("something went wrong");
}
异步/等待只是语法糖(在后台,异步/等待使用Promises).该代码基本上等同于上面的代码
async/await is just syntax sugar (behind the scenes, async/await use Promises). This code is basically equivalent to the above code
function getRandomNumberAsync(max: number): Promise<number> {
return Promise.resolve(Math.floor(Math.random() * Math.floor(max)));
}
getRandomNumberAsync(100).then(result => {
console.log(result);
}).catch(e => {
console.error("something went wrong");
})
我可以看到在您的代码中,您正在使用return await
,这是多余的.甚至还有 eslint规则防止这种情况
I can see that in your code, you're using return await
which is redundant. There's even an eslint rule to prevent this
您的代码应如下所示
const Table = {
getOne: async (id: string): Promise<QueryResult> => {
return db.query('SELECT * FROM table WHERE id=$1', [id]);
},
}
// "getOne" should be called like this
try {
const result = await Table.getOne("YOUR_ID");
// handle result
} catch (e) {
// handle error
}
除非您要处理getOne
它应该看起来像这样
const Table = {
getOne: async (id: string): Promise<QueryResult | string> => {
try {
return await db.query("SELECT * FROM table WHERE id=$1", [id]);
} catch (e) {
return "something went wrong";
}
},
}
这篇关于如何在TypeScript中键入node-postgres异步查询函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!