The interface cannot be exported to angular 2 module?

I tried to export the interface in the NgModule declaration and export and get this error already in the editor (Visual Studio code): [ts] 'MyInterface' only refers to a type, but is being used as a value here.

Here is a sample Change-1 code:

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

One part of the explanation I found in the response to this post is : "because interfaces are erased at runtime in TypeScript." I am currently reorganizing my application for functional modules, so I cannot test it right now: can I only use interfaces by importing from './mypathto/my.interface'?

+6
source share
2 answers

You cannot export an interface. You can export only:

  • Other modules
  • Components
  • Directives
  • Pipes

NgModule is an angular concept and should not be confused with typescript module. To make a third-party user who uses your module that can use your interface, you must create a .d.ts definition .d.ts with your module.

If you want to use the interface inside another NgModule, you should simply use:

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

Also, do not put the interface in the declaration array, this is used only for pipes / components / directives.

If you want your interface to be used outside the library, you must add it to the export of your index.ts :

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

Well, you can actually export an interface, but not in the way you are trying to do.

First create the interfaces.ts file by typing

ng g interface <interface_name>

Example interface file:

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

After changing the file to your needs, you can import only one, all or selected interfaces, for example:

 import { Auction } from './interfaces'; 

or

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

If for a chance you know how to share interfaces around the world. let me know: Angular how to exchange interfaces through the application

+3
source

Source: https://habr.com/ru/post/1015105/


All Articles