Recently, I encountered an issue with an external library that doesn't have types. The code snippet looks something like this:
var method1 = require('./method1');
var method2 = require('./method1');
module.exports = {
method1: method1,
method2: method2
}
To address this, I created a directory named "typings/lib-name" and added "typings" in typeRoots. Inside this folder, there is an index.d.ts file with the following content:
declare module "lib-name" {
import { Method1Interface, ... } from "./modules/method1.d.ts";
import { Method2Interface, ... } from "./modules/method2.d.ts";
export {
Method1Interface,
Method2Interface,
...
}
}
However, when I attempted to use it in my code:
import lib from "lib-name"
lib.method1()
I encountered this error:
TS2339: Property 'method1' does not exist on type 'typeof import("lib-name")'
. As a beginner in TypeScript, I would appreciate some guidance on where I might have gone wrong.
EDITED I made some changes by adding a default export in the module:
declare module "lib-name" {
import { Method1Interface, ... } from "./modules/method1.d.ts";
import { Method2Interface, ... } from "./modules/method2.d.ts";
export {
Method1Interface,
Method2Interface,
...
}
default export {
method1: Method1Interface
}
}
Unfortunately, after this modification, method1 ended up having the type 'any', which is confusing to me.
EDITED2 I managed to resolve the issue by defining the methods before the default export:
declare module "lib-name" {
import { Method1Interface, ... } from "./modules/method1.d.ts";
import { Method2Interface, ... } from "./modules/method2.d.ts";
const method1: Method1Interface;
const method2: Method2Interface;
export {
Method1Interface,
Method2Interface,
...
}
default export {
method1,
method2
}
}