簡體   English   中英

打字稿:請求類型上不存在“已解碼”屬性

[英]Typescript: Property 'decoded' does not exists on type Request

我在javascript中有這段代碼:

if (token) {

    // verifies secret and checks exp
    jwt.verify(token, Config.Secret, function(err, decoded) {      
      if (err) {
        return res.json({ success: false, message: 'Failed to authenticate token.' });    
      } else {
        // if everything is good, save to request for use in other routes
        req.decoded = decoded;    
        next();
      }
    });

  } else {

    // if there is no token
    // return an error
    return res.status(403).send({ 
        success: false, 
        message: 'No token provided.' 
    });

  }

想要將其重寫為打字稿,但收到錯誤Property decoded does not exists on type Request

任何想法如何解決這個問題?

如果您不想創建一個擴展 Request 的新類,您可以將 request 作為對象訪問,例如:

req['decoded'] = decoded;

如果它仍然向您拋出,您可能必須將 req 轉換為對象(打字稿):

(<Object>req)['decoded'] = decoded;

您甚至可以將 req 強制轉換為輸入 any 並將訪問解碼為屬性(打字稿):

(<any>req).decoded = decoded;

您將需要使用聲明合並來為自定義Request字段添加類型定義。 為此,請創建一個.d.ts文件:

declare module Express {
  export interface Request {
    decoded: string;
    // etc.
  }
}

並將其添加到您的編譯上下文中,以便編譯器將類型定義與express.d.ts的類型定義合並。

即使可能,我也不會合並來自同名模塊的接口。 我寧願創建一個新的自定義界面,您甚至可以在使用它的同一個文件中聲明它。 (否則,只需導出它)

import {Request, Response} from "express";

interface CustomRequest extends Request {
    decoded: string;
}

這更干凈,而且更接近OOP。

該錯誤意味着來自 express 的原始Request類型沒有任何具有該名稱的字段。

您有兩種選擇來解決這個問題,第一個如Vadim Macagon 所指出的,您可以創建一個聲明模塊文件並添加您的自定義字段,這樣該字段將在每個請求中都可用。

declare module Express {
  export interface Request {
    decoded: string;
    // etc.
  }
}

選項二您可以創建一個自定義接口來擴展原始請求並添加您的解碼字段。

export default interface ICustomRequest extends Request {
  token: string;
}

然后在你的代碼中

app.post('/', function (req: ICustomRequest, res) {
  req.decoded = decoded; // No errors here
});

第一個解決方案是將自定義字段“添加”到Request ,第二個解決方案是添加字段並從 Request 擴展。

在您的情況下,我將使用第一個解決方案來避免每次必須使用請求中的decoded字段時編寫 ICustomRequest(或您選擇的任何名稱),文件.d.ts不需要在您的代碼中導入這樣您就可以創建文件並完成。

我的“解碼”只是 user_id 字符串,我像這樣解決了這個問題:

req.body.decoded = decoded;    
next();

我最近遇到了同樣的問題,我按照之前評論和這個 repo 中的解決方案,我仍然遇到同樣的問題。 在進行更多挖掘之后,它似乎是 ts-node 的一個錯誤。

要解決這個問題,您需要使用 --files 標志運行您的服務器

因此,如果您通常運行服務器 ts-node ./src/server.ts 或 nodemon ./src/server.ts 將其更改為 ts-node --files ./src/server.ts 或 nodemon --files ./src /server.ts

之后,我能夠在啟動服務器時擺脫 VScode 錯誤和錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM