【问题标题】:Unable to import class that was exported two times (Typescript)无法导入两次导出的类(Typescript)
【发布时间】:2016-04-04 14:12:33
【问题描述】:

我无法导入已导出两次的类。

a.ts

import * as moduleB from "./b";
export class A {
  b: moduleB.B;
  constructor() {
    this.b = new moduleB.B();
    this.b.hello();
  }
}

b.ts

import {C} from "./c";
export const B = C;

c.ts

export class C {
  hello() {
    console.log("hello");
  }
}

错误信息是:

a.ts(3,14): error TS2305: Module '"b"' has no exported member 'B'.

问题似乎是C的类型可能没有用“export const B = C;”导出。如果我更改“b:moduleB.B;”,错误就会消失只是“b:任何;”。 我该如何解决这个问题?

在 b.ts 中使用默认导出会起作用,但我想在 b.ts 中导出几个东西,所以这不是一个选项。我正在使用 Typescript 1.7.5。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    当您在a.ts 中声明属性b : moduleB.B 时,您将b 定义为类型 moduleB.B,但您已将moduleB.B 定义为常量。因为 const 是对 C 的构造函数的引用,所以 new moduleB.B() 会编译。

    你可以改为在b.ts 中写export type B = C,但这只会导出类型别名,这意味着b : moduleB.B 会编译,但new moduleB.B() 不会,因为你这样做了不导出构造函数。

    b.ts 中使用export {C as B}(完整别名)来实现您想要实现的目标。

    【讨论】:

    • 太棒了。这解决了我的问题。我不知道这种导出语法。
    猜你喜欢
    • 2018-02-24
    • 2018-02-21
    • 2021-10-23
    • 2021-01-16
    • 1970-01-01
    • 2015-08-23
    • 2017-01-22
    • 2017-01-29
    • 2016-03-31
    相关资源
    最近更新 更多