类型'T'不可分配给类型'Dictionary <string>

时间:2019-09-14 04:22:59

标签: javascript node.js typescript

我正在尝试在我的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; 

enter image description here

1 个答案:

答案 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;
}

Playground