如何将字符串属性转换为 TypeScript 数组中的自定义类型?
我有一个扩展 MongoDB 文档的接口,以及一些扩展该接口的示例数据。 界面是这样的:
export default interface IModel extends Document {
_id: ObjectId;
name: string;
data:string;
}
样本数据符合这个界面。对象 ID 类型看起来像一串数字和字母。但是,当我在 _id 字段中为示例数据定义值时,它会引发错误,因为 TypeScript 将其键入为字符串,并且类型应为 ObjectId。那么如何将 id 的值转换为 ObjectId 类型呢?
我正在尝试做这样的事情:
export const ModelSampleData: IModel = {
"_id": toObjectId(240nfkfn38943),
"name": "model",
"data": "modelstuffetc"
}
感谢任何帮助!
I have an interface that is extending a MongoDB document, and some sample data that is extending that interface.
The interface is like this:
export default interface IModel extends Document {
_id: ObjectId;
name: string;
data:string;
}
The sample data matches this interface. The object ID type looks like a string of numbers and letter. However, when I define a value for the sample data in the _id fields, it throws an error because TypeScript types it as a string and the type should be ObjectId. So how can I cast the value of the id to be of type ObjectId?
I am trying to do something like this:
export const ModelSampleData: IModel = {
"_id": toObjectId(240nfkfn38943),
"name": "model",
"data": "modelstuffetc"
}
Appreciate any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据这个链接,您可以将字符串类型转换为
objectId
,如下所示:according to this link, you can cast your string type to
objectId
like so:您需要做的就是删除“”,您尝试复制响应并将其分配给 ModelSampleData,它是 json 对象,而不是 javascript 对象,如果您想使用,请使用 JSON.parse
下面两个示例都应该有效
或
All you need to do is remove "", you tried to copy response and assign it to ModelSampleData which is json object, not javascript object, if you want to use then use JSON.parse
below both samples should work
or