【问题标题】:An interface cannot be exported in an angular 2 module?无法在 Angular 2 模块中导出接口?
【发布时间】:2017-02-19 20:24:44
【问题描述】:

我尝试在 NgModule 声明中导出接口并导出并在编辑器(Visual Studio 代码)中出现此错误:[ts] 'MyInterface' only refers to a type, but is being used as a value here.

这里是示例代码Edit-1

import { NgModule }           from '@angular/core';
import { CommonModule }       from '@angular/common';
import { FormsModule }        from '@angular/forms';
import { MaterialModule }     from '@angular/material';
import { MyInterface }        from './my.interface';
import { MyService }          from './my.service';

@NgModule({
  imports:      [ CommonModule, FormsModule,  MaterialModule.forRoot()  ],
  declarations: [ MyInterface],//<- this is causing the message
  exports:      [ MyInterface],
  providers:    [ MyService ]
})
export class MyModule { }

我找到了in the answer to this post 的部分解释:“因为 TypeScript 中的接口在运行时被擦除”。 我目前正在将我的应用程序重构为功能模块,所以我现在无法对其进行测试:我只能通过从 './mypathto/my.interface' 导入来使用接口吗?

【问题讨论】:

  • 发布您的代码。导出和导入接口在这里工作得很好。
  • 你想在哪里使用它?作为提供者? I tried to export an interface in a NgModule-declaration 什么意思?
  • 我已将示例代码添加到问题中。谢谢@yurzui,您的链接正在回答问题:“TypeScript 接口不是有效的令牌”。

标签: angular typescript


【解决方案1】:

您不能导出接口。您只能导出:

  1. 其他模块
  2. 组件
  3. 指令
  4. 管道

NgModule 是一个角度概念,不应与打字稿模块混淆。要使使用您的模块的第三方能够使用您的界面,您应该使用您的模块创建一个.d.ts 定义文件。

如果你想在你的另一个 NgModule 中使用接口,你应该使用:

import {InterfaceName} from 'path/to/ngmodule/to/interface';

另外,不要在声明数组中放置接口,这仅用于管道/组件/指令。

如果您希望您的界面可以在库之外使用,您应该将其添加到您的index.ts 的导出中:

export {InterfaceName} from 'path/to/ngmodule/to/interface';

【讨论】:

  • 感谢 PierreDuc 的“完整答案”,这澄清了很多。我找到了this documentation on .d.ts
  • 但是,我如何与第三方通信,库的传入数据应该遵循特定的模式,我想在接口内指定?这会更容易,例如在 npm 上发布节点包时,不是吗?
【解决方案2】:

其实你可以导出一个界面,但不是你想要的方式。

首先通过输入生成interfaces.ts文件

ng g interface &lt;interface_name&gt;

接口文件示例:

export interface Auction{ $key?:string; $auctioneer:string;  ... }
export interface Item{ $key?:string; condition?:string; description?:string; ...}
export interface Bid{  $key?:string;  amount:number;  auction:string; ...}

根据您的需要修改文件后,您可以只导入一个、全部或选择的接口,如下所示:

import { Auction } from './interfaces';

import * as interfaces from './interfaces'; 
// then you have to call interfaces.Auction

如果您有机会知道如何在全球范围内共享接口,请。在这里告诉我:Angular how to share interfaces across the app

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 2017-10-01
    • 2017-04-04
    相关资源
    最近更新 更多