首页 > 解决方案 > 将 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

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

标签: typescript

解决方案


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

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

推荐阅读