简体   繁体   中英

How can I convert a string property to a custom type within a TypeScript array?

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!

according to this link , you can cast your string type to objectId like so:

export const ModelSampleData: IModel = {
  "_id": ObjectId("240nfkfn38943"),
  "name": "model",
  "data": "modelstuffetc"
}

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

import { ObjectId } from 'mongodb';

export default interface IModel extends Document{
    _id: ObjectId ;
    name: string;
    data:string;
}

export const ModelSampleData1: IModel = JSON.parse(`{
    "_id": ObjectId(240nfkfn38943),
    "name": "model",
    "data": "modelstuffetc"
}`);

or

export const ModelSampleData: IModel = <IModel> {
    _id:  new ObjectId("240nfkfn38943"),
    name: "model",
    data: "modelstuffetc"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM