Search code examples
node.jsmongodbtypescriptmongoose-schema

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 ?


Solution

  • 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.