scotthovestadt / schema-object

Enforce schema on JavaScript objects, including type, transformation, and validation. Supports extends, sub-schemas, and arrays.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add a SchemaObjectSchema interface and export SchemaObjectInstance in typescript definitions?

anthony-o opened this issue · comments

I'm using schema-object in Angular and I want to store results of SchemaObject.new in a local variable.

Today I'm forced to write this in my Angular service:

import * as SchemaObject from 'schema-object';

interface SchemaObjectInstance<T> {
  populate(values: T): void;
  toObject(): T;
  clone(): SchemaObjectInstance<T>;
  clear(): void;
  getErrors(): Array<{
    errorMessage: string;
    setValue: any;
    originalValue: any;
    fieldSchema: {
      name: string;
      index: string;
    }
    schemaObject: SchemaObjectInstance<T>;
  }>;
  clearErrors(): void;
  isErrors(): boolean;
}

interface SchemaObjectSchema<T> {
  new (values?: T): T & SchemaObjectInstance<T>;
}

@Injectable()
export class MyService {
  // Schema cache
  metadataStructureToSchema = new Map<any, SchemaObjectSchema<any>>();

  // somewhere in my code:
  private createSchema(metadataStructure: any) {
    this.metadataStructureToSchema.set(metadataStructure, new SchemaObject(metadataStructure, {keysIgnoreCase: true});
  }
}

In schemaobject.d.ts, would it be possible to add an intermediate interface (like the one I called SchemaObjectSchema) and export all those interfaces?

Something like this (I don't know how to export all the interfaces):

interface SchemaObjectInstance<T> {
  // [...] nothing to change here
}

interface SchemaObjectSchema<T> {
  new (values?: T): T & SchemaObjectInstance<T>;
}

declare module 'schema-object' {

    interface SchemaObject {
        new <T>(schema: { [key in keyof T]: any }, options?: any): SchemaObjectSchema<T>;
    }
    const SO: SchemaObject;
    export = SO;

}