Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

725
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda