我有 express.js 控制器,但我不能使用 req.params
錯誤是Property 'id' is missing in type 'ParamsDictionary' but required in type 'IParam'.
我需要id
從引數中獲取字串型別
import { Request, Response } from 'express'
interface IParam {
id: string
}
const Update = (req: Request, res: Response) => {
const { id }: IParam = req.param // The error occured here
}
export default Update
uj5u.com熱心網友回復:
您的主要問題是您試圖將req.params.id
(字串)轉換為IParam
(物件)。
你通常可以只使用這個......
const { id } = req.params;
因為Express 將默認引數型別定義為
export interface ParamsDictionary {
[key: string]: string;
}
否則,您可以強烈鍵入Request
以包含您的引數
const Update = (req: Request<IParam>, res: Response) => {
const { id } = req.params;
}
uj5u.com熱心網友回復:
您可能應該在這里使用型別斷言:
interface IParam {
id: string
}
const Update = (req: Request, res: Response) => {
const { id } = req.param as unknown as IParam
}
export default Update
一個斷言告訴 TypeScript 你知道你在做什么。以前,你有一個型別注釋,所以 TypeScript 真的很想跳進去檢查分配。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/527579.html
標籤:打字稿表示
下一篇:從父類傳遞時道具未定義