英文:
How to infer type of callback parameters for typescript
问题
我正在尝试将TypeScript添加到我的代码中,但似乎无法推断出某些类型,更确切地说是回调函数的参数。
Item.find({}, (err, items) => {...} // 缺少回调参数的类型
"Item" 是 mongoose 中的一个模型。
正如您在下面的文档中所看到的,没有指定回调参数的类型:
https://mongoosejs.com/docs/api/model.html#model_Model-find
我应该只是将 "any" 作为类型吗?还是有一些我不知道的方法可以找到它?
英文:
I am trying to add typescript to my code and I do not seem to find how to infer some types. more precisely parameters of a callback.
Item.find({},(err, items) => {...} //missing type for callback parameters
"Item" is a Model from mongoose.
As you can see in the doc below, nothing specify the type of the callback parameters :
https://mongoosejs.com/docs/api/model.html#model_Model-find
Am I supposed to just put "any" as a type ? Or is there some way I am missing out to find it?
答案1
得分: 1
我通过为我使用的模式声明了一个接口来解决了这个问题。
interface IItem{...}
const itemSchema = new Schema<IItem> (...)
const Item = model<IItem>("Item", itemSchema)
因此,解决方案如下:
Item.find({}, (err: string, items: Array<IItem>) => {...}
文档中有解释:
https://mongoosejs.com/docs/typescript.html
英文:
I solved the problem by declaring an interface for the schema I was using.
interface IItem{...}
const itemSchema = new Schema<IItem> (...)
const Item = model<IItem>("Item", itemSchema)
So for the solution being :
Item.find({}, (err: String, items: Array<IItem>){...}
It was explained in the doc :
https://mongoosejs.com/docs/typescript.html
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论