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

Time:03-19

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!

CodePudding user response:

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"
}

CodePudding user response:

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"
}
  • Related