Currently I am tasked with creating node modules from our Vanilla JS and moving them to typescript. I rewrote them as classes, added some functionality, wrote a legacy wrapper and the corresponding web pack configuration. The problem is that some of these modules are singletons, so instead of exporting the class by default we want to export an class instance as default. The problem is that I don't get the type checking to work properly:
import DebugJs from 'debug';
const test = (test: DebugJs) => {
test.console('warn', 'does', 'respond', 'with a warning', test);
};
The problem here is that DebugJs is not recognized as a type. So currently I have to import an additional Interface in order to set the type properly.
Just for comparsion, this is what I currently do instead:
import DebugJs, { DebugJsInterface } from 'debug';
const test = (test: DebugJsInterface) => {
test.console('warn', 'does', 'respond', 'with a warning', test);
};
I tried around with namespaces and module declaration, but to be honest, as someone who is totally new to node module creation and quite new to typescript I don't really know what I am doing there.
Here is my current index.d.ts file setup
import DebugJs from './src/debugJsModule';
import {DebugLevels} from "./src/types/types";
export interface DebugJsInterface {
levels:DebugLevels;
enabled:boolean;
level:number;
console(...arguments: any): void;
enableDebug(): void;
disableDebug(): void;
setLevel(level:number): void;
}
export interface Module {
DebugJs: DebugJsInterface;
}
export default DebugJs;
declare module 'debug';
Here the DebugJsInterface is defined as a work around. I am also a little puzzled since I thought that the idnex.d.ts should only have type information. But if I don't export the class instance from here my module import won't be recognized as a class properly.
This is my debugJsModule wrapper which returns a class instance:
import DebugJs from './class/DebugJs';
import { DebugLevels } from 'debug/src/types/types';
const DebugJsInstance: DebugJs = new DebugJs();
export default DebugJsInstance;
The class itself is simply defined as a class and exported as a default export as well
class DebugJs { ... }
Just to be clear, functionality wise everything works, all I want to figure out how I can have the proper type of my importet class instance by using the same import name, in this case DebugJs, without having to rely on an extra importet interface as a workaround.
DebugJSshould absolutely work as a type if it is a class or a type. However, if you're exporting the singleton as default it wont work. It is not clear whatDebugJsis and how you're exporting the type/class and the singleton.import DebugJsand though that file was merely reexporting things, me bad