【发布时间】:2021-03-15 14:44:27
【问题描述】:
我有一个没有类型的外部库。看起来像这样:
var method1 = require('./method1');
var method2 = require('./method1');
module.exports = {
method1: method1,
method2: method2
}
我创建了一个目录“typings/lib-name”(在 typeRoots 中添加了“typings”)。在这个文件夹中,我有 index.d.ts 文件,并且有这样的内容:
declare module "lib-name" {
import { Method1Interface, ... } from "./modules/method1.d.ts";
import { Method2Interface, ... } from "./modules/method2.d.ts";
export {
Method1Interface,
Method2Interface,
...
}
}
当我尝试在我的代码中使用它时:
import lib from "lib-name"
lib.method1()
我得到:TS2339: Property 'method1' does not exist on type 'typeof import("lib-name")'
我刚从 TS 开始,所以我会很感激解释我哪里出错了。
已编辑 我在模块中添加了默认导出:
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
}
}
但是method1的类型为any。我不明白为什么。
EDITED2 当我在默认导出之前定义方法时,它可以工作。
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
}
}
【问题讨论】:
-
您使用了
import lib from "lib-name",但我在您的index.d.ts中没有看到任何export default -
你说得对,但是当我添加
export default { method1: Method1Interface }然后 method1 的类型为“any”我不明白 O>O -
显示
Method1Interface定义 -
当我在默认导出之前定义方法时它可以工作(参见我的编辑2)。我想我不能在导出中使用
method1: Method1Interface语法。感谢您的帮助:-)
标签: javascript typescript