Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

724
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda