Markus
Markus

Reputation: 597

Cannot find namespace 'SchemaTypes'

I've some typescript problem with using mongoose...

import { SchemaDefinition, SchemaTypeOpts, SchemaTypes } from 'mongoose';

export interface ILockedSchemaDefinition extends SchemaDefinition {
  locked?: SchemaTypeOpts<SchemaTypes.Boolean>;
}

The SchemaTypes namespace in the interface body is not found.

But SchemaTypes is found when I create my schema:

import { SchemaTypes, Types } from 'mongoose';
import { ILockedSchemaDefinition } from './i_locked_schema_definition';
import { LockedSchema } from './locked_schema';

const schema = new LockedSchema<ILockedSchemaDefinition>({
  x: {
    maxlength: 200,
    required: true,
    type: SchemaTypes.String
  }
}

So looks like some bug in the typings of mongoose.
Have you seen this before and do you know a workaround?

Modified from comment below to:

import { Schema, SchemaDefinition, SchemaTypeOpts } from 'mongoose';

export interface ILockedSchemaDefinition extends SchemaDefinition {
  locked?: SchemaTypeOpts<typeof Schema.Types.Boolean>;
}

Now I've a problem with setting default value:

import { Schema, SchemaOptions } from 'mongoose';
import { BaseSchema } from './base_schema';
import { ILockedSchemaDefinition } from './i_locked_schema_definition';

export class LockedSchema<T extends ILockedSchemaDefinition> extends BaseSchema<T> {
  constructor(definition?: T, options?: SchemaOptions) {
    if (!definition.locked) {
      definition.locked = {
        default: false,
        type: Schema.Types.Boolean
      };
    }
    super(definition, options);
  }
}

This exception:

Type '{ default: boolean; type: typeof Boolean; }' is not assignable to type 'SchemaTypeOpts'. Types of property 'default' are incompatible. Type 'boolean' is not assignable to type 'typeof Boolean | DefaultFn<typeof Boolean>'

Upvotes: 1

Views: 960

Answers (1)

Romain Deneau
Romain Deneau

Reputation: 3061

There's a trick for the types:

  • SchemaTypes is purely JavaScript
  • Schema.Types works with TypeScript

Try the following snippet that seems to work at least regarding the TypeScript compilation:

import { Schema, SchemaDefinition, SchemaTypeOpts } from 'mongoose';

export interface ILockedSchemaDefinition extends SchemaDefinition {
  locked?: SchemaTypeOpts<typeof Schema.Types.Boolean | boolean>;
}

export class LockedSchema<T extends ILockedSchemaDefinition> /* extends BaseSchema<T> */ {
  constructor(definition?: T /* , options?: SchemaOptions */) {
    if (!definition.locked) {
      definition.locked = {
        default: false,
        type: Schema.Types.Boolean
      };
    }
    // super(definition, options);
  }
}

Upvotes: 2

Related Questions