Search code examples
typescripttypescript-typingstsc

TypeScript enforce all files in a folder export a class which extends another class


If I have a folder:

jobs/
  a.ts
  b.ts
  c.ts

is there a way to use TypeScript so that all the files in the jobs folder export the same interface?

I'd like for a.ts, b.ts, c.ts to all export the same interface.


Solution

  • Not really sure what you're looking for, but you can do this:

    In jobs directory:

    a.ts:

     export interface MyInterface {
       color: string;
     }
    

    b.ts:

     export interface MyInterface {
       name: string;
     }
    

    c.ts:

      export interface MyInterface {
        age: number;
      }
    

    Then, is some other file, you can have this:

     import { MyInterface } from './jobs/a';
    
     export class SomeClass implements MyInterface {
         color: string;
     }
    

    In a different file, you can have this:

     import { MyInterface } from './jobs/b';
    
     export class SomeClass implements MyInterface {
         name: string;
     }
    

    And in yet another different file, you can have this:

     import { MyInterface } from './jobs/c';
    
     export class SomeClass implements MyInterface {
         age: number;
     }
    

    Unless there is a very good, bulletproof reason for this, I don't think this is a good idea at all. It can get really easy to get confused and import/modify the wrong thing and cause yourself unnecessary headaches.

    Technically, all three of the interface exports from a, b, & c could have the same parameters (like they all have name: string)... it's basically the same thing... maybe you're hedging against changes later? You can extend interfaces for that FYI.

    Can you further explain what you're trying to accomplish?

    • EDIT *

    You can't have this all in the same file:

    import { MyInterface } from './jobs/a';
    import { MyInterface } from './jobs/b';
    import { MyInterface } from './jobs/c';
    
     export class SomeClass implements MyInterface {
         age: number;
     }
    
     export class SomeOtherClass implements MyInterface {
         color: string;
     }
    
     export class SomeOtherOtherClass implements MyInterface {
         name: string;
     }