How to declare and import typescript interfaces in a separate file

前端 未结 4 1422
长发绾君心
长发绾君心 2020-12-12 20:14

I want to define several interfaces in their own file in my typescript-based project, from which I\'ll implement classes for production as well as mocks for testing. However

4条回答
  •  遥遥无期
    2020-12-12 20:36

    Export only a few interfaces

    Without spreading multiple exports, you can group them in one single export {} block (in this case, no file default type should be declared):

    // interfaces.ts
    interface IWords {
      [key: string]: string; 
    }
    
    interface INumbers {
      [key: string]: number; 
    }
    
    interface IBooleans {
      [key: string]: boolean; 
    }
    
    interface IValues {
      [key: string]: string | number; 
    }
    
    interface IStructures {
      [key: string]: INumbers | IBooleans | IValues;
    }
    
    export {
      // not exporting IWords | INumbers
      IBooleans,
      IValues,
      IStructures,
    }
    

    Import example

    import { IBooleans, IValues, IStructures } from 'interfaces';
    
    const flags: IBooleans = { read: true, write: false, delete: false };
    
    const userFile: IValues = { user: 1, username: 'One', file: 'types.txt' };
    
    const userContext: IStructure = {
      file: userFile,
      permissions: flags,
      counts: { views: 3, writes: 1 } // => INumbers (lint: try to remove IValues from IStructures)
    };
    

提交回复
热议问题