【问题标题】:TypeScript types to external libraryTypeScript 类型到外部库
【发布时间】: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


【解决方案1】:

我解决了我的问题。首先,我没有默认导出。接下来,默认导出不应该使用这样的语法:

default export {
  method1: Method1Interface
}

我在默认导出之前定义了method1,然后一切正常。

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
  }
}

【讨论】:

    猜你喜欢
    • 2021-09-25
    • 1970-01-01
    • 2018-05-25
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多