user358089
user358089

Reputation:

TypeScript - Declare vs Export - Best Practices?

Short and sweet, is it better practice to define my own interfaces with declare or with export?

// i.something.d.ts
export default interface ISomething {
    myValue: string;
} 

// something.ts
import ISomething from 'i.something';

export class Something implements ISomething {...}

vs.

// i.something.d.ts
declare interface ISomething {
    myValue: string;
} 

// something.ts
export class Something implements ISomething {...}

Of course, even declare doesn't work ambiently if it has to import another type of its own. (Unless there is a better way to do it)

// i.something-else.d.ts
import SomeBiggerThing from '...';
import SomeKindOfType from '...';

declare interface ISomethingElse extends SomeBiggerThing {
    myValue: SomeKindOfType;
} 

// something-else.ts
// ISomethingElse isn't available unless I import it, because it imports its own stuff.
import ISomethingElse from 'i.something-else';

export class Something implements ISomethingElse {...}

Upvotes: 22

Views: 12772

Answers (1)

Nathan Friend
Nathan Friend

Reputation: 12814

Most large/mature TypeScript libraries avoid relying on ambient declarations and instead export anything that needs to be reused outside of the current file. For example, the Angular codebase has an interfaces.ts file for each module which is imported into each file that needs to reference the interfaces:

https://github.com/angular/angular/tree/0b1f5d21270063b2019b11a9494397916d3977d6/packages/http/src/interfaces.ts

This has a few advantages:

  • All types used in a file are explicitly referenced through an import statement at the top of the file.
  • It's easier to export your module's interfaces to make them available to consumers of your module. In order to export an ambient interface, you would need to define the interface directly in your module's main file (only local declarations can be exported from a module).
  • It's more JavaScript-y. Modern JavaScript relies on import and export statements, while ambient type contexts are a TypeScript-only concept.

Upvotes: 25

Related Questions