找不到名称空间“ SchemaTypes”

时间:2018-06-25 07:55:30

标签: typescript mongoose

我在使用猫鼬时遇到打字稿问题...

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

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

在接口主体中找不到SchemaTypes命名空间。

但是在创建架构时会找到SchemaTypes:

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
  }
}

所以看起来像猫鼬的打字错误。
您以前看过此书吗,知道解决方法吗?

从下面的注释修改为:

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

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

现在我在设置默认值时遇到了问题:

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);
  }
}

此例外:

键入'{默认值:布尔值;类型:typeof布尔值; }”不可分配给“ SchemaTypeOpts”类型。属性“默认”的类型不兼容。不能将类型'boolean'分配给'typeof Boolean | DefaultFn <布尔类型>'

1 个答案:

答案 0 :(得分:1)

对于这些类型有一个窍门:

  • SchemaTypes完全是JavaScript
  • Schema.Types与TypeScript一起使用

请尝试以下至少对TypeScript编译有效的代码段:

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);
  }
}