Marcus Krahl
Marcus Krahl

Reputation: 684

Merge Typescript interface and class in different files

In Typescript it is possible to merge an interface and a class if they have the same name and are in the same file:

interface Test {
  example(input: 'a number'): number;
  example(input: 'a string'): string;
}

class Test {
  example(input: string): any {
    //return something
  }
}

const obj = new Test();
obj.example('a number'); //return type is number
obj.example('a string'); //return type is string
obj.example('something else'); //return type is any

However there does not seem to be a way to split these interface definitions into multiple files, e.g.:

//test.interface.ts
export interface Test {
  example(input: 'a number'): number;
  example(input: 'a string'): string;
}

//test.class.ts
import "./test.interface.ts";

class Test {
  example(input: string): any {
    //return something
  }
}

const obj = new Test();
obj.example('a number'); //return type is any but should be number
obj.example('a string'); //return type is any but should be string
obj.example('something else'); //return type is any

What is the correct way to split such an interface definition between a class and an actual interface into multiple files?

Upvotes: 2

Views: 2666

Answers (1)

Marcus Krahl
Marcus Krahl

Reputation: 684

The solution to this problem is to redeclare the "hosting" typescript module to augment its definition:

//test.interface.ts
declare module './test.class.ts' {
  interface Test {
    example(input: 'a number'): number;
    example(input: 'a string'): string;
  }
}

//test.class.ts
import "./test.interface.ts";

class Test {
  example(input: string): any {
    //return something
  }
}

const obj = new Test();
obj.example('a number'); //return type is number
obj.example('a string'); //return type is string
obj.example('something else'); //return type is any

Upvotes: 5

Related Questions