Typescript: how to break definitions into separate files

Refresh

November 2018

Views

74 time

2

I'm using a single definition file for a whole TS project, and it's working fine.

I'd like to know if it is possible to break the ts' definitions into separate files by feature/component. That way, each component would have it's own definitions, augmenting the main definition namespace, just like the way @types does regarding angular and its plugins (animate, ui.router and so on). But I'm not certain about how to do this.

My folder structure:

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

My definition files:

// 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?   
}

My 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/**"
  ]
}

Is it possible? How can I do this?

1 answers

1

Один из способов заключается в использовании reference pathи declareпространств имен вместо их экспорта.

shared.d.ts

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

login.d.ts

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

index.d.ts

/// <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.

введите описание изображения здесь