darksoulsong
darksoulsong

Reputation: 15337

Typescript: how to break definitions into separate files

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?

Upvotes: 3

Views: 359

Answers (1)

Shaun Luttin
Shaun Luttin

Reputation: 141662

One way is to use reference path and to declare namespaces instead of exporting them.

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;
}

Here is a screenshot of the above working in VSCode.

enter image description here

Upvotes: 2

Related Questions