An interface cannot be exported in an angular 2 module?

后端 未结 2 1332
慢半拍i
慢半拍i 2021-01-01 13:27

I tried to export an interface in a NgModule-declaration and export and getting this error already in the editor (Visual Studio Code): [ts] \'MyInterface\' only refers

相关标签:
2条回答
  • 2021-01-01 13:36

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

    First generate interfaces.ts file by typing

    ng g interface <interface_name>

    Example of 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 modifying the file to your needs you can import just one, all or chosen interfaces like this:

    import { Auction } from './interfaces';
    

    or

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

    If per chance you know how to share interfaces globally pls. let me know here: Angular how to share interfaces across the app

    0 讨论(0)
  • 2021-01-01 13:56

    You cannot export an interface. You can only export:

    1. Other modules
    2. Components
    3. Directives
    4. Pipes

    NgModule is an angular concept and should not be confused with a typescript module. To make a third party, who uses your module, able to use your interface, you should create a .d.ts definition file with your module.

    If you want to use a interface inside another NgModule of yours, you should just use:

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

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

    If you want your interface to be usable outside of an library, you should add it to the export of your index.ts:

    export {InterfaceName} from 'path/to/ngmodule/to/interface';
    
    0 讨论(0)
提交回复
热议问题