Ts-loader: require.d.ts clashes with node.d.ts

Created on 27 Jan 2016  路  9Comments  路  Source: TypeStrong/ts-loader

When I declare require as per the documentation in a require.d.ts

 declare var require: {
    <T>(path: string): T;
    (paths: string[], callback: (...modules: any[]) => void): void;
    ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void) => void;
};

it then clashes with the node.d.ts declare var require: NodeRequire;

error TS2403: Subsequent variable declarations must have the same type.
        Variable 'require' must be of type '{ <T>(path: string): T; (paths: string[],
 callback: (...modules: any[]) => void): void; ensure: (...', but here has type '
NodeRequire'.

is there a workaround?

question

Most helpful comment

Change require.d.ts to something like this instead:

interface NodeRequire {
   ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void) => void;
}

That will extend the NodeRequire interface defined by node.d.ts to include the ensure definition.

All 9 comments

You don't need to use a require.d.ts. Just remove it and use the definition in node.d.ts instead.

Thanks James, that works for calls to require('module-name') but throws an error for require.ensure

error TS2339: Property 'ensure' does not exist on type 'NodeRequire'.

I know its not a ts-loader thing specifically but maybe you know the solution?

Change require.d.ts to something like this instead:

interface NodeRequire {
   ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void) => void;
}

That will extend the NodeRequire interface defined by node.d.ts to include the ensure definition.

brilliant! thanks for the dig out

Just for completeness - here is with the optional named chunk param:

interface NodeRequire {
    ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void, name?:string ) => void;
}

i have some problem. and update it will have module name.
interface NodeRequire { ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void, name?: string) => void; }

How to ensure type safety? Something went wrong for me. I'm getting the error as property 'default' does not exist on type {}. Here my lazy module is exported as export default "Hello" and the consumer is using the below code.
require.ensure([], (require) => { this.content= require('./lazy').default; })

Thank you @johnnyreilly
The error was on typecasting while using and is resolved by (<any>require('./lazy')).default;

Was this page helpful?
0 / 5 - 0 ratings