提问人:Prosto_Oleg 提问时间:10/17/2023 更新时间:10/18/2023 访问量:46
属性“X”在类型“FastifyContext<unknown>上不存在
Property 'X' does not exist on type 'FastifyContext<unknown>'
问:
我想将该字段添加到 FastifyContext 接口。为此,我创建了以下文件结构:token: string
projectDir
|__src
| |__@types
| | |__fastify
| | | |__index.d.ts
| |__api
| | |__authHook.ts
|__tsconfig.json
内容:src/@types/fatify/index.d.ts
declare module 'fastify' {
export interface FastifyContext<ContextConfig>{
token: string
}
}
内容src/api/authHook.ts
import {FastifyRequest, FastifyReply} from "fastify";
export default async function authHook(request: FastifyRequest, reply: FastifyReply): Promise<void>{
// Some logic
const token = "example_token" // some result from logic
request.context.token = token;
}
内容:tsconfig.json
{
"compilerOptions": {
...
"typeRoots": ["src/@types"],
...
}
}
但是当我运行代码时,我收到以下错误:
Property 'token' does not exist on type 'FastifyContext<unknown>'.
我做错了什么?
答:
1赞
Meowster
10/18/2023
#1
import { onRequestHookHandler } from "fastify";
declare module "fastify" {
export interface FastifyRequestContext {
token: string;
}
}
const authHook: onRequestHookHandler = async function (request, reply) {
const token = "example_token";
request.context.token = token;
};
export default authHook;
评论
0赞
Prosto_Oleg
10/18/2023
它正在工作。但是我想将所有外部库类型存储在一个单独的目录中。我能做到吗?
0赞
Meowster
10/18/2023
是的。不要更改 typeRoots。只需将您的d.ts文件放在 SRC 中的任何目录中
评论