英文:
Type 'void | RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[] | ResultSetHeader' is not assignable to type 'IUser[]'
问题
我有一个名为Users
的类,如下所示:
class Users {
static async findAll(req: Request, res: Response, next: NextFunction): Promise<IUser[]> {
const rows = await Pools.execute("SELECT * FROM users")
.then((rows) => {
return rows[0];
})
.catch(err => console.log(err));
next();
return rows;
}
}
但是我在最后一行return rows;
处遇到了错误:
类型 'void | RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[] | ResultSetHeader' 不能分配给类型 'IUser[]'。
类型 'void' 不能分配给类型 'IUser[]'。
这是IUser
接口的声明:
import { RowDataPacket } from "mysql2"
interface IUser extends RowDataPacket {
id?: number;
email: string;
password: string;
username: string;
admin: boolean;
created_at: Date;
}
export { IUser };
我知道rows[0]
的结构如下:
[
{
"id": 1,
"email": "admin@u.com",
"password": "12345",
"username": "admin@u.com",
"admin": 1,
"created_at": "2023-01-06T02:31:14.000Z"
},
{
"id": 2,
"email": "u@u.com",
"password": "12345",
"username": "u@u.com",
"admin": 0,
"created_at": "2023-01-06T03:08:20.000Z"
}
]
为什么会发生这种情况,我该如何修复它?
英文:
I have a Users
class like following:
class Users {
static async findAll(req: Request, res: Response, next: NextFunction) : Promise<IUser[]> {
const rows = await Pools.execute("SELECT * FROM users" )
.then((rows) => {
return rows[0];
})
.catch(err => console.log(err));
next();
return rows;
}
}
But I get the error at the last line return rows;
:
> Type 'void | RowDataPacket[] | RowDataPacket[][] | OkPacket |
> OkPacket[] | ResultSetHeader' is not assignable to type 'IUser[]'.
> Type 'void' is not assignable to type 'IUser[]'.
This is the declaration of IUser
interface:
import { RowDataPacket } from "mysql2"
interface IUser extends RowDataPacket {
id?: number;
email: string;
password: string;
username: string;
admin: boolean;
created_at: Date;
}
export {IUser};
I know the rows[0]
is like the following:
[
{
"id": 1,
"email": "admin@u.com",
"password": "12345",
"username": "admin@u.com",
"admin": 1,
"created_at": "2023-01-06T02:31:14.000Z"
},
{
"id": 2,
"email": "u@u.com",
"password": "12345",
"username": "u@u.com",
"admin": 0,
"created_at": "2023-01-06T03:08:20.000Z"
}
]
Why this happens and how can I fix it?
答案1
得分: 0
我不确定是否找到了正确的解决方案,但通过更改以下行,错误将消失:
const rows = await Pools.execute("SELECT * FROM users")
到:
const rows: any = await Pools.execute("SELECT * FROM users")
英文:
I am not sure if I found the correct solution but the error will gone by changing the following line:
const rows = await Pools.execute("SELECT * FROM users" )
To:
const rows : any = await Pools.execute("SELECT * FROM users" )
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论