【问题标题】:Cannot import exported interface - export not found无法导入导出的接口 - 找不到导出
【发布时间】:2017-04-12 00:26:17
【问题描述】:

我将问题简化为这个例子:

test.model.ts

export class A {
    a: number;
}

export interface B {
    b: number;
}

test.component.ts

import { Component, Input } from '@angular/core';
import { A, B } from './test.model';

@Component({
    selector: 'test',
    template: '<h1>test</h1>'
})
export class TestComponent {

    //This works fine
    @Input() foo: A;

    //Does NOT work - export 'B' was not found in './test.model'
    @Input() bar: B;

}

当我想使用界面时,我收到以下警告:

WARNING in ./src/app/.../test.component.ts
21:76 export 'B' was not found in './test.model'

但是,使用 是可以的。有什么提示吗?

更新:似乎与此问题有关:https://github.com/webpack/webpack/issues/2977

【问题讨论】:

  • 这里不是已经回答了吗? stackoverflow.com/questions/30270084/…
  • 我不这么认为 - 该问题涉及我不使用的默认导出。还是谢谢。
  • 抱歉,没有正确阅读
  • 这是运行时错误还是编译错误?
  • 这是一个编译警告。

标签: angular typescript ecmascript-6


【解决方案1】:

根本原因在于 Typescript 和转译。一旦 TypeScript 代码被转译,接口/类型就消失了。它们不再存在于发出的文件中。

虽然类型被删除,但导入/导出不一定。原因是存在歧义,并且编译器并不总是能确定导出的内容是类型还是值。

当使用 TypeScript 3.8 及更高版本时,您需要在 test.component.ts 中做的只是这样:

import { A } from './test.model';
import type { B } from './test.model';

【讨论】:

    【解决方案2】:

    昨天我在这里发现了另一个问题以及将导出接口声明为单独文件的解决方案。每个文件有一个接口,它对我有用,没有任何警告。

    【讨论】:

    • 这对我有用,这里解释了原因:github.com/angular/angular-cli/issues/…
    • 我收到此错误,即使它是文件中的唯一接口(但也有其他导出,例如 mergeInterfaces(left, right) 方法)。这似乎是一个诚实的错误,而不是一个功能。
    【解决方案3】:

    您还可以通过使用Typescript 3.8 中称为Type-Only Imports and Exports 的新功能来解决此问题。

    所以这意味着你可以像这样导入有问题的类型A

    import { B } from './test.model';
    import type { A } from './test.model';
    

    另外请注意,Angular 似乎只支持来自 Angular 9.1 and above 的 Typescript 3.8。

    我也推荐阅读this "Leveraging Type-Only imports and exports with TypeScript 3.8" post for more details

    【讨论】:

      【解决方案4】:

      消除警告的另一种方法是对a union of the interface with itself 进行稍微令人反感的黑客攻击。

      @Input() bar: B | B;
      

      【讨论】:

        【解决方案5】:

        这对我有用:

        @Input() bar: B | null;
        

        使用 Angular 4.4.3 + Typescript 2.3.4

        【讨论】:

        • 如果您允许 null 作为有效输入值,这将起作用(否则它将违反类型安全)。
        【解决方案6】:

        我在它自己的myinterface.ts 文件中定义了一个接口,然后运行 ​​Karma 测试时出现此错误。运行ng serve 时我没有看到问题。在myinterface.ts 文件中再添加 1 个未使用的 const 的 export 解决了这个问题:

        export interface IMyInterface {
            ...
        }
        export const A = 'A';
        

        【讨论】:

          猜你喜欢
          • 2015-08-23
          • 2017-02-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-31
          • 1970-01-01
          • 2017-05-04
          • 1970-01-01
          相关资源
          最近更新 更多