【发布时间】:2021-06-11 20:24:09
【问题描述】:
首先,我知道这个话题看起来很像 this other topic 谈论 使用 Typescript 扩展 Express Request 对象
基本上,我尝试做同样的事情,但这次使用Polka
有人能做到吗?
我走的路径类似于this
在项目根杆我创建了这个文件夹结构:
app/
├─ src/
│ ├─ @types/
│ │ ├─ polka/
│ │ │ ├─ index.d.ts
我在index.d.ts中添加了这个
import * as polka from "polka";
declare global {
namespace polka {
interface Request {
foo: string;
}
}
}
我还通过添加以下内容更新了我的tsconfig.json:
"typeRoots": [ "@types" ]
我为请求分配值的中间件如下所示
import type { Middleware } from "polka";
export const dummyMiddleware: Middleware = (req, res, next) => {
req.foo = "hello";
next();
};
这样做我有这个打字稿错误:
Property 'foo' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs,
当我查看 Polka Middleware definition 时,我看到这种类型是通用的。
我试图做这样的事情
import type { Middleware } from "polka";
export const dummyMiddleware: Middleware<{foo : string}> = (req, res, next) => {
req.foo = "hello";
next();
};
但是错误信息只变成了这个
Property 'foo' does not exist on type 'Request<{ foo: string; }, any, any, ParsedQs, Record<string, any>>'.ts(2339)
那么,问题是,声明合并是实现这一目标的最佳方式吗?如果是,您是否有适当的方法来实现这一目标?
一点上下文,这个中间件将用于seeding Sapper session data。
版本:
- “打字稿”:“^4.0.3”
- “波尔卡”:“下一个”
- “@types/polka”:“^0.5.2”,
完整的 TypeScript 配置:
{
"extends": "@tsconfig/svelte/tsconfig.json",
"compilerOptions": {
"module": "esnext",
"lib": ["DOM", "ES2017", "WebWorker", "ESNext"],
"strict": true
},
"include": ["src/**/*", "src/node_modules/**/*"],
"exclude": ["node_modules/*", "__sapper__/*", "static/*"],
"typeRoots": [ "@types" ]
}
免责声明:
我是波尔卡和打字的新手,所以我错过了一些明显的东西并非不可能
【问题讨论】:
标签: typescript sapper polka