req.params无法拿到foodname和price
来源:11-57 【泛型递归+复杂泛型 交叉类型 综合实战】 跨越式的提高复杂泛型运用能力

crazyones110
2021-10-08
import { router } from '../util/router'
import MethodType from '../util/methodtype'
import { RequestHandler } from 'express'
// 枚举
type MyClassDecorator = <T extends { new(...args: any): any }>
(targetClass: T) => any
export function Controller(reqRootPath: string): MyClassDecorator {
return function (targetClass): any {
console.log("控制器装饰器执行...");
for (let methodname in targetClass.prototype) {
let routerpath = Reflect.getMetadata("path", targetClass.prototype, methodname) // S100 这一行里routerpath是any类型啊
let methodType: MethodType = Reflect.getMetadata("methodType", targetClass.prototype, methodname)
const targetMethodfunc: RequestHandler = targetClass.prototype[methodname];
let middleawres: RequestHandler[] = Reflect.getMetadata("middleawares",
targetClass.prototype, methodname)
if (routerpath && methodType) {
if (middleawres) {
router[methodType](routerpath, ...middleawres, targetMethodfunc) // S101 也就是说这里routerpath传进去的是any类型, 根本不可能推断出来req.params类型的
} else {
router[methodType](routerpath, targetMethodfunc)
}
}
}
}
}
我试了在request-decorator里加泛型, 没用, 调用Reflect.getMetadata
就会让原来的类型丢失了, 全部变成any
写回答
2回答
-
keviny79
2021-10-09
问题解决结果和思路
00 -
keviny79
2021-10-09
1.为什么获取不到foodName
这个问题底层 Request 的params 在编译期间 类型识别定义它的泛型的默认值为 ParamsDictionary=
interface ParamsDictionary {
[key: string]: string;
}
[key: string]: 索引接口自然获取不到foodName 和 price
2 .也可以不管,因为get("/") 和下面参数取值在一起
3. 我这里有一个唯一的解决方法和i已经实现的结果,但我这次先只提供一个解决方法的思路和自动提示的结果,给你留一个思考的空间,你可以根据我的截图中提示思考下 见截图
022021-10-09
相似问题