typescriptdynamoose

Exporting a Dynamoose Typescript model


  1. The dynamoose library provides the following signature for constructing a model:
    model: {
        <T extends Document>(name: string, schema?: SchemaDefinition | Schema, options?: Partial<import("./Model").ModelOptions>): T & Model<T> & ModelDocumentConstructor<T>;
        defaults: any;
    };
  1. Consumption in a TypeScript file is being done as follows:
import * as dynamoose from 'dynamoose';
...
const ExampleRepository = dynamoose.model(
  schemaName,
  ExampleSchema,
);

export default ExampleRepository;
  1. Compilation produces the error:
Exported variable 'ExampleRepository' has or is using name 'ModelDocumentConstructor' from external module ".../node_modules/dynamoose/dist/index" but cannot be named.

Other answers to similar questions on SO would suggest that the ModelDocumentConstructor should be imported. TS4023: Exported Variable <x> has or is using name <y> from external module but cannot be named

However the interface itself is not exported, so cannot be imported.


Solution

  • Since ModelDocumentConstructor is not exported, I have implemented the following solution as a workaround. Create a second wrapper object to export, which contains the methods you need.

    For example:

    const Model = dynamoose.model('MyObj', Schema, {
      create: false,
      update: false,
    });
    
    async function add(obj: {}) {  
      try {
        await Model.create(obj);
      } catch (e) {
        console.error(e);
      }
    }
    
    async function findMany(obj: { [key: string]: any }) {  
      try {
        return await Model.batchGet(obj);
      } catch (e) {
        console.error(e);
      } 
    }
    
    ...
    
    export const myObjDb = {
      find,
      findMany,
      add,
      remove,
      update,
      updateMany,
    };