Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
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!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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"
}
about 4 years ago · Juan Pablo Isaza Report

0

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"
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!