Angular how to share interfaces across the app

Viewed 2573

So I have a interfaces.ts file which looks something like this:

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; ...}
and so on  ...

Now I can import those interfaces in each component/service by calling:

import { Auction,Item,Bid } from './interfaces';

But how can I import the interfaces.ts file so all interfaces will be available globally?

2 Answers

You will have to import interfaces.ts in every component/service where you're going to want to use those interfaces.

The closest thing you can do (which saves some writing, maybe) is:

    import * as foo from './interfaces';

    var item: foo.Item;
    var auction: foo.Auction;
    var bid: foo.Bid;

If you do not import interfaces.ts, it can simply not find the names of the interfaces.

In your app module add this, where InterfaceOne and InterfaceTwo will be your interfaces. The downside to this is that your app module will get bigger the more interfaces you have. It would be better to have the interfaces in a separate file and done in the same way. I'm not sure how to do this though.

declare global {

   export interface InterfaceOne {},
   export interface InterfaceTwo {},
   //more interfaces

}

Related