代码之家  ›  专栏  ›  技术社区  ›  darksoulsong

Typescript:如何将定义分解为单独的文件

  •  3
  • darksoulsong  · 技术社区  · 9 年前

    我想知道是否有可能按特征/组件将ts的定义分解为单独的文件。这样,每个组件都会有自己的定义,从而扩展主定义命名空间,就像这样 @types

    我的文件夹结构:

    index.ts
    index.d.ts
    app
        shared
            shared.ts
            shared.d.ts
            user.ts
            config.ts
        login
            login.ts
            login.d.ts
            login.component.ts
            login.component.html
    

    我的定义文件:

    // shared.d.ts
    export namespace shared {
        interface IConfig {
            url: string;
        }
    }
    
    // login.d.ts
    export namespace login {
        interface ILogin {
            logIn(): Promise<any>;
            logOut(): Promise<any>;
        }
    }
    
    // index.d.ts
    import * as sharedModule from './app/shared/shared';
    import * as loginModule from './app/login/login';
    
    declare module App {
        // extend the App module with the imported definitions. How?   
    }
    

    我的tsconfig。json

    {
      "compilerOptions": {
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false,
        "typeRoots": ["node_modules/@types/", "src/"]
      },
      "compileOnSave": false,
      "filesGlob": [
        "src/**/*.ts",
        "src/**/*.tsx",
        "!node_modules/**"
      ]
    }
    

    1 回复  |  直到 9 年前
        1
  •  2
  •   Shaun Luttin    9 年前

    一种方法是使用 reference path declare 名称空间,而不是导出它们。

    共享。d、 输电系统

    declare namespace shared {
        interface IConfig {
            url: string;
        }
    }
    

    登录。d、 输电系统

    declare namespace login {
        interface ILogin {
            logIn(): Promise<any>;
            logOut(): Promise<any>;
        }
    }
    

    指数d、 输电系统

    /// <reference path="shared.d.ts" />
    /// <reference path="login.d.ts" />
    
    declare module "App" {
        // we now have access to the `shared` namespace.
        const config: shared.IConfig;
    }
    

    下面是上面在VSCode中工作的屏幕截图。

    enter image description here

    推荐文章