My current task involves converting our Vanilla JS node modules to TypeScript. I have rewritten them as classes, added new functionality, created a legacy wrapper, and set up the corresponding Webpack configuration. However, I am facing an issue with singleton modules. Instead of exporting the class by default, we want to export a class instance as default. The problem arises when it comes to type checking:
import DebugJs from 'debug';
const test = (test: DebugJs) => {
test.console('warn', 'does', 'respond', 'with a warning', test);
};
The issue is that DebugJs is not recognized as a type. Currently, I have to import an additional interface to properly set the type.
For comparison, this is what I currently do:
import DebugJs, { DebugJsInterface } from 'debug';
const test = (test: DebugJsInterface) => {
test.console('warn', 'does', 'respond', 'with a warning', test);
};
I have tried experimenting with namespaces and module declarations. But being new to node module creation and TypeScript, I find myself unsure about my approach.
Here is my current setup in the index.d.ts file:
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';
In this setup, DebugJsInterface serves as a workaround. It puzzles me because I thought index.d.ts should only contain type information. However, if I don't export the class instance here, my module import won't recognize it as a class properly.
My debugJsModule wrapper 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 defined as a simple class and exported as a default export as well.
class DebugJs { ... }
To clarify, all functionalities are working fine. My main goal is to understand how I can ensure the proper typing of my imported class instance using the same name (DebugJs) without relying on an extra imported interface as a workaround.