在不同文件中合并Typescript接口和类

时间:2018-10-24 11:39:21

标签: typescript

在Typescript中,如果接口和类具有相同的名称并且位于同一文件中,则可以合并它们:

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

但是,似乎没有办法将这些接口定义拆分为多个文件,例如:

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

将此类接口定义在类和实际接口之间拆分为多个文件的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

此问题的解决方案是重新声明“托管”打字稿模块以扩大其定义:

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