【问题标题】:error TS2749: 'IRequestWithUser' refers to a value, but is being used as a type here. Did you mean 'typeof IRequestWithUser'?错误 TS2749:“IRequestWithUser”指的是一个值,但在这里被用作一种类型。您的意思是“typeof IRequestWithUser”吗?
【发布时间】:2020-12-22 22:26:24
【问题描述】:

我在 express 库中扩展 Request 以包含用户属性:

import { Request } from 'express';

export default interface RequestWithUser extends Request {
  user: {
    user_name: string;
    password: string;
  }
}

第一个参数注释出现标题错误:

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'?
*/

我不相信接口就是价值。它们应该纯粹是类型。那么是什么导致了这个错误呢?

也试过了

typeof IRequestWithUser 这导致No overload matches this call

【问题讨论】:

    标签: node.js typescript


    【解决方案1】:

    也许您的代码 sn-ps 中缺少某些内容,但我在 Typescript 3.9 上遇到的唯一错误是与您稍后在问题中提到的过载错误有关。

    因为.post() 调用正在寻找一个需要Request 类型的回调,所以您不能将req 参数键入为IRequestWithUser。这是因为,虽然IRequestWithUser 将包含Request 的所有属性,但Typescript 编译器无法保证您计划在req 中拥有的额外属性在运行回调时会存在。

    扩展 Express 类型的 recommended way 是使用 interface merging。这允许您完全“重新定义”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;
            }
        }
    }
    

    您的编译器应自行选择此文件并使用原始 Request 类型支持您的新属性。如果您使用类似ts-node 的东西,您可能需要在tsconfig.json 中设置明确的typeRoots

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 2021-08-02
      • 1970-01-01
      • 2021-01-12
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 2020-03-23
      相关资源
      最近更新 更多