js-schema icon indicating copy to clipboard operation
js-schema copied to clipboard

typescript TypeError: js_schema_1.default is not a function

Open ghost opened this issue 8 years ago • 1 comments

Following TypeScript code

import {Schema} from 'js-schema';
import schema from 'js-schema';

let obj: Schema = schema({ foo: String, bar: String });

is transpiled into followin JS code

var js_schema_1 = require('js-schema');
var obj = js_schema_1.default({ foo: String, bar: String });

which leads to the error

TypeError: js_schema_1.default is not a function

How do I prevent transpiling this default-property?

I found a similar issue here: https://github.com/Microsoft/TypeScript/issues/5565

ghost avatar Aug 05 '16 10:08 ghost

The module js-schema should be imported in typescript using

import * as schema from 'js-schema';

rather than

import schema from 'js-schema';

I tried it on my current project and it raise an on error from typescript in my editor but pass the compilation and the generated javascript file works perfectly.

This typescript error seems to be an issue with the @types/js-schema types definitions module, I changed it's index.d.ts file and it now works fine. the index.d.ts now looks like that:

declare module 'js-schema'
{
    function schema(definition: any): schema.Schema;

    namespace schema {
        interface Schema {
            (obj: any): boolean; // test obj against the schema
        }

        interface NumberConstructor {
            min(n: number): NumberConstructor;
            max(n: number): NumberConstructor;
            below(n: number): NumberConstructor;
            above(n: number): NumberConstructor;
            step(n: number): NumberConstructor;
        }

        interface StringConstructor {
            of(charset: string): StringConstructor;
            of(length: number, charset: string): StringConstructor;
            of(minLength: number, maxLength: number, charset: string): StringConstructor;
        }

        interface ArrayConstructor {
            like(arr: Array<any>): ArrayConstructor;
            of(pattern: any): ArrayConstructor;
            of(length: number, pattern: any): ArrayConstructor;
            of(minLength: number, maxLength: number, pattern: any): ArrayConstructor;
        }

        interface ObjectConstructor {
            like(obj: any): ObjectConstructor;
            reference(obj: any): ObjectConstructor;
        }

        interface FunctionConstructor {
            reference(func: Function): FunctionConstructor;
        }
    }

    export = schema;
}

roblabat avatar Apr 21 '17 13:04 roblabat