[英]error TS2749: 'IRequestWithUser' refers to a value, but is being used as a type here. Did you mean 'typeof IRequestWithUser'?
I am extending Request
in express
library to contain a user property:我在
express
库中扩展Request
以包含用户属性:
import { Request } from 'express';
export default interface RequestWithUser extends Request {
user: {
user_name: string;
password: string;
}
}
The title error appears in the first parameter annotation:标题错误出现在第一个参数注释中:
import IRequestWithUser from '../shared/interfaces/isRequestWithUser';
const router: Router = Router();
router.post('/myRoute', async (req: IRequestWithUser, res: Response) => {
/*
error TS2749: 'IRequestWithUser' refers to a value,
but is being used as a type here. Did you mean
'typeof IRequestWithUser'?
*/
I don't believe interfaces are values.我不相信接口是值。 They should purely be types.
它们应该纯粹是类型。 So what is causing this error?
那么是什么导致了这个错误呢?
Also tried也试过
typeof IRequestWithUser
This results in No overload matches this call
typeof IRequestWithUser
这导致No overload matches this call
Perhaps there's something missing from your code snippets, but the only error I get on Typescript 3.9 is one that relates to the overload error that you allude to later in your question.也许您的代码片段中缺少某些内容,但我在 Typescript 3.9 上遇到的唯一错误是与您稍后在问题中提到的重载错误有关的错误。
Because the .post()
call is looking for a callback that expects type Request
, you can't type your req
argument as IRequestWithUser
.由于
.post()
调用正在寻找需要类型Request
的回调,因此您不能将req
参数键入为IRequestWithUser
。 This is because, although IRequestWithUser
will contain all properties of Request
, the Typescript compiler can't guarantee that the extra properties you plan to have in req
will be there when the callback is run.这是因为,尽管
IRequestWithUser
将包含Request
所有属性,但 Typescript 编译器无法保证您计划在req
拥有的额外属性在运行回调时会存在。
The recommended way to extend Express types is to use interface merging .扩展 Express 类型的推荐方法是使用接口合并。 This allows you to "redefine" the
Request
type altogether, but it's a global definition so it gets messy:这允许你完全“重新定义”
Request
类型,但它是一个全局定义,所以它变得混乱:
// definitions/express/index.d.ts
import * as express from 'express' // Unfortunately, you need some kind of import here to make this a valid module.
declare module "express-serve-static-core" {
export interface Request {
user: {
user_name: string;
password: string;
}
}
}
Your compiler should pick this file up on its own and support your new property using the original Request
type.您的编译器应自行选择此文件并使用原始
Request
类型支持您的新属性。 You might need to have an explicit typeRoots
set in your tsconfig.json
if you're using something like ts-node
though.您可能需要有一个明确的
typeRoots
在您设置tsconfig.json
如果你正在使用类似ts-node
虽然。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.