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

723
Views
Mongoose Schema type as a custom interface from TypeScript?

enter image description here

I´d like to store a custom object that has the StationRating interface attributes, can somebody help me ?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

It's possible, but it requires some boilerplate. Issues are:

  • Interfaces and types in TS do not exist in emitted code

  • While you could go in the other direction - create a schema object and make an interface/type out of it - schema object values must be constructors, eg Number, which is not the same thing as something with a number type.

But you can create a type that maps the constructor types to their primitive types (eg Number to number), then use that to turn the schema object into the type you want:

type ConstructorMapping<T> =
    T extends NumberConstructor ? number :
    T extends StringConstructor ? string : never; // etc: continue as needed

const schemaObj = {
  score: Number,
  user_id: String,
  station_id: String,
  description: String,
};

type SchemaObj = typeof schemaObj;
type StationRating = {
    [prop in keyof SchemaObj]: ConstructorMapping<SchemaObj[prop]>
};

Then use schemaObj when calling new Schema, and you'll also have the following usable type:

type StationRating = {
    score: number;
    user_id: string;
    station_id: string;
    description: string;
}

Is it worth it? I'm not sure. For smaller objects, maybe not. For larger objects, maybe so. You might prefer just to write out the type and the schema object.

over 4 years ago · Santiago Trujillo 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!