我正在尝试在我的get路由中编写请求的接口。你能帮忙吗? 该接口应扩展默认的请求接口,但必须包含我的id参数。
看到以下错误:
{
"owner": "typescript",
"code": "2430",
"severity": 8,
"message": "Interface 'IGetCustomRequest<T>' incorrectly extends interface 'Request'.\n Types of property 'params' are incompatible.\n Type 'T' is not assignable to type 'Dictionary<string>'.",
"source": "ts",
"startLineNumber": 17,
"startColumn": 11,
"endLineNumber": 17,
"endColumn": 28
}
import express = require('express');
interface IGetParams {
id: string
}
interface IGetCustomRequest<T> extends express.Request {
params: T
}
var router = require('express').Router();
router.get("/:id", (req: IGetCustomRequest<IGetParams>, res: express.Response) => {
console.log('sent', req.params)
res.json(`${req.params.id} get params -----------------------`);
});
module.exports = router;
答案 0 :(得分:1)
params
类型的属性express.Request
被限制为具有字符串键和值的Dictionary
类型。您在T
中的IGetCustomRequest
不受限制,因此编译器会抱怨Request
的扩展错误。
看看快递类型:
// copied from @types/express-serve-static-core
export interface Dictionary<T> {
[key: string]: T;
}
export type ParamsDictionary = Dictionary<string>;
export type ParamsArray = string[];
export type Params = ParamsDictionary | ParamsArray;
type Request<P extends Params = ParamsDictionary> = {
params: P;
};
作为解决方案,您可以以T
的形式限制<T extends ParamsDictionary>
:
interface IGetCustomRequest<T extends ParamsDictionary> extends Request {
params: T;
}