我正在使用 apollo server使用 typescript ,我无法在解析器中获取上下文参数以获取 name
位于 context
的房产是一个字符串。现在输入为 any
我希望将其输入为 string
.我还看到 context
当我希望它是一个特定的接口(interface)时,参数是任何类型的。无论如何要告诉上下文和它的属性,我希望它是什么类型,而不是它们都被输入为 any
?
const server = new ApolloServer({
typeDefs: gql`
type Query {
test: String
}
`,
resolvers: {
Query: {
test(parent: any, args: any, context, info: any) {
context.name // name is typed as "any" when I'd like it to be typed as "string"
}
}
},
context() {
return {
name: 'John Doe'
}
}
})
我试图做这样的事情,但这会引发错误。context<{ name: string }>() {
return {
name: 'John Doe'
}
}
我确实通过明确地告诉上下文它需要什么来让它工作,但这种方式似乎有点乏味,因为我必须导入 Context
进入每个解析器文件并手动转换。interface Context {
name: string
}
const server = new ApolloServer({
...
resolvers: {
Query: {
test(parent: any, args: any, context: Context, info: any) {
context.name // name is typed as "string" here because I used "context: Context" explicitly
}
}
}
...
})
最佳答案
如果您是 graphql-code-generator要生成您的类型,您可以在 codegen.yml 中配置上下文类型:
generates:
src/generated/graphql.ts:
config:
contextType: "src/types#Context"
然后定义你的上下文类型:export interface Context {
username: string;
}
现在context
解析器方法的参数将输入 Context
无需导入类型或进行任何其他更改。
关于typescript - 如何在 Apollo Server 中正确键入上下文对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63159116/