gpt4 book ai didi

typescript - 使用TypeScript,如何强烈键入mysql查询结果

转载 作者:行者123 更新时间:2023-12-01 11:14:25 25 4
gpt4 key购买 nike

我是Typescript的新手,无法确定我是否在正确输入查询结果。这是我的代码的本质...

import mysql2, {Pool} from "mysql2";
const pool: Pool = mysql2.createPool({...}).promise();

interface IUser {
uid : number;
uname : string;
}

class UserController {

public async getUser(id: number): Promise<IUser> {
const [rows]: Array<{rows: IUser}> = await pool.query(
"SELECT * FROM `users` WHERE `email` = ?",["me@me.org"]);
return rows;
}
}

TypeScript编译器(3.3.1)提示我的 return rows语句。

TS2740: Type '{rows: IUser;}' is missing the following properties from type 'IUser': uid and uname.



如果我忽略 // @ts-ignore的返回,那么一切都很好。我把我的物体放回原处,没有任何错误。

难道我做错了什么?

我做了一些更改,但是对于TypeScript为什么不提示,我实在感到困惑。似乎根本不对。
    class UserController {

public async getUser(id: number): Promise<{rows: IUser}> {
const [rows]: Array<{rows: IUser}> = await pool.query(
"SELECT * FROM `users` LIMIT 3");
return rows;
}
}

这是正确的吗???

所以,没有,这全都错了。

当我想到 query返回 [rows, fields]时,它也开始变得更有意义了。我认为@ joesph-climber经过一些调整后的语法是正确的。

这对我来说很有用...
    class UserController {

public async getUser(id: number): Promise<Array<{rows: IUser}>> {
const [rows]: [Array<{rows: IUser}>] = await pool.query(
"SELECT * FROM `users` LIMIT 3");
return rows;
}
}

这也可行,并且可能更容易理解。
    class UserController {

public async getUser(id: number): Promise<IUser[]> {
const [rows]: [IUser[]] = await pool.query(
"SELECT * FROM `users` LIMIT 3");
return rows;
}
}

最佳答案

// the function should return a Promise that resolves to 
{ uid: number, uname: string }

// but typeof rows is
{ rows: { uid: number, uname: string } }

执行该示例,我得到的结果是这样的:
[ TextRow { uid: 1, uname: 'foo', email: 'foo@mail.com' } ]

因此,pool.query返回一个以IUser数组作为第一个元素的数组。

Returning multiple users:


class UserController {
// returns all users
public async getUsers(): Promise<Array<IUser>> {
const [rows]: [Array<IUser>] = await pool.query(
"SELECT * FROM `user`", []);
return rows; // rows is Array<IUser> so it matches the promise type
}
}

Returning a specific user:


class UserController {
public async getUser(id: number): Promise<IUser> { // Note the
const [rows]: [Array<IUser>] =
await pool.query("SELECT * FROM `user` WHERE `email` = ?",
["foo@mail.com"]);
// If email is unique as it would be expected it will
// return a single value inside an array
// rows is still Array<IUser>
return rows[0]; // rows[0] is an IUser
}
}

关于typescript - 使用TypeScript,如何强烈键入mysql查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54583950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com